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
55,066
Correctly set IsRetargetable for source assemblies
Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
333fred
2021-07-23T00:55:50Z
2021-07-24T00:08:23Z
a3b5d0f87fbdceadf6d3d1b024aca4736e3e079e
c58fbd573ea1ca0273ef3878782baab73d5201c8
Correctly set IsRetargetable for source assemblies. Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
./src/EditorFeatures/CSharpTest/TypeInferrer/TypeInferrerTests.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 System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.TypeInferrer; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.TypeInferrer { public partial class TypeInferrerTests : TypeInferrerTestBase<CSharpTestWorkspaceFixture> { protected override async Task TestWorkerAsync(Document document, TextSpan textSpan, string expectedType, TestMode mode) { var root = await document.GetSyntaxRootAsync(); var node = FindExpressionSyntaxFromSpan(root, textSpan); var typeInference = document.GetLanguageService<ITypeInferenceService>(); ITypeSymbol inferredType; if (mode == TestMode.Position) { var position = node?.SpanStart ?? textSpan.Start; inferredType = typeInference.InferType(await document.ReuseExistingSpeculativeModelAsync(position, CancellationToken.None), position, objectAsDefault: true, cancellationToken: CancellationToken.None); } else { inferredType = typeInference.InferType(await document.ReuseExistingSpeculativeModelAsync(node?.Span ?? textSpan, CancellationToken.None), node, objectAsDefault: true, cancellationToken: CancellationToken.None); } var typeSyntax = inferredType.GenerateTypeSyntax().NormalizeWhitespace(); Assert.Equal(expectedType, typeSyntax.ToString()); } private async Task TestInClassAsync(string text, string expectedType, TestMode mode) { text = @"class C { $ }".Replace("$", text); await TestAsync(text, expectedType, mode); } private async Task TestInMethodAsync(string text, string expectedType, TestMode mode) { text = @"class C { void M() { $ } }".Replace("$", text); await TestAsync(text, expectedType, mode); } private static ExpressionSyntax FindExpressionSyntaxFromSpan(SyntaxNode root, TextSpan textSpan) { var token = root.FindToken(textSpan.Start); var currentNode = token.Parent; while (currentNode != null) { if (currentNode is ExpressionSyntax result && result.Span == textSpan) { return result; } currentNode = currentNode.Parent; } return null; } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConditional1() { // We do not support position inference here as we're before the ? and we only look // backwards to infer a type here. await TestInMethodAsync( @"var q = [|Goo()|] ? 1 : 2;", "global::System.Boolean", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConditional2(TestMode mode) { await TestInMethodAsync( @"var q = a ? [|Goo()|] : 2;", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConditional3(TestMode mode) { await TestInMethodAsync( @"var q = a ? """" : [|Goo()|];", "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestVariableDeclarator1(TestMode mode) { await TestInMethodAsync( @"int q = [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestVariableDeclarator2(TestMode mode) { await TestInMethodAsync( @"var q = [|Goo()|];", "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestVariableDeclaratorNullableReferenceType(TestMode mode) { await TestInMethodAsync( @"#nullable enable string? q = [|Goo()|];", "global::System.String?", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesce1() { await TestInMethodAsync( @"var q = [|Goo()|] ?? 1;", "global::System.Int32?", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesce2(TestMode mode) { await TestInMethodAsync( @"bool? b; var q = b ?? [|Goo()|];", "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesce3(TestMode mode) { await TestInMethodAsync( @"string s; var q = s ?? [|Goo()|];", "global::System.String", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesce4() { await TestInMethodAsync( @"var q = [|Goo()|] ?? string.Empty;", "global::System.String?", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesceWithErrorType() { // We could be smart and infer this as an ErrorType?, but in the #nullable disable case we don't know if this is intended to be // a struct (where the question mark is legal) or a class (where it isn't). We'll thus avoid sticking question marks in this case. // https://github.com/dotnet/roslyn/issues/37852 tracks fixing this is a much fancier way. await TestInMethodAsync( @"ErrorType s; var q = [|Goo()|] ?? s;", "ErrorType", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBinaryExpression1(TestMode mode) { await TestInMethodAsync( @"string s; var q = s + [|Goo()|];", "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBinaryExpression2(TestMode mode) { await TestInMethodAsync( @"var s; var q = s || [|Goo()|];", "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBinaryOperator1(TestMode mode) { await TestInMethodAsync( @"var q = x << [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBinaryOperator2(TestMode mode) { await TestInMethodAsync( @"var q = x >> [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestAssignmentOperator3(TestMode mode) { await TestInMethodAsync( @"var q <<= [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestAssignmentOperator4(TestMode mode) { await TestInMethodAsync( @"var q >>= [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestOverloadedConditionalLogicalOperatorsInferBool(TestMode mode) { await TestAsync( @"using System; class C { public static C operator &(C c, C d) { return null; } public static bool operator true(C c) { return true; } public static bool operator false(C c) { return false; } static void Main(string[] args) { var c = new C() && [|Goo()|]; } }", "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestConditionalLogicalOrOperatorAlwaysInfersBool(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { var x = a || [|7|]; } }"; await TestAsync(text, "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestConditionalLogicalAndOperatorAlwaysInfersBool(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { var x = a && [|7|]; } }"; await TestAsync(text, "global::System.Boolean", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] | true; } }"; await TestAsync(text, "global::System.Boolean", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] | b | c || d; } }"; await TestAsync(text, "global::System.Boolean", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference3(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { var x = a | b | [|c|] || d; } }"; await TestAsync(text, "global::System.Boolean", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference4() { var text = @"using System; class C { static void Main(string[] args) { var x = Goo([|a|] | b); } static object Goo(Program p) { return p; } }"; await TestAsync(text, "Program", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference5(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { var x = Goo([|a|] | b); } static object Goo(bool p) { return p; } }"; await TestAsync(text, "global::System.Boolean", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference6() { var text = @"using System; class C { static void Main(string[] args) { if (([|x|] | y) != 0) {} } }"; await TestAsync(text, "global::System.Int32", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference7(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] | y) {} } }"; await TestAsync(text, "global::System.Boolean", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] & true; } }"; await TestAsync(text, "global::System.Boolean", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] & b & c && d; } }"; await TestAsync(text, "global::System.Boolean", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference3(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { var x = a & b & [|c|] && d; } }"; await TestAsync(text, "global::System.Boolean", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference4() { var text = @"using System; class C { static void Main(string[] args) { var x = Goo([|a|] & b); } static object Goo(Program p) { return p; } }"; await TestAsync(text, "Program", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference5(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { var x = Goo([|a|] & b); } static object Goo(bool p) { return p; } }"; await TestAsync(text, "global::System.Boolean", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference6() { var text = @"using System; class C { static void Main(string[] args) { if (([|x|] & y) != 0) {} } }"; await TestAsync(text, "global::System.Int32", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference7(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] & y) {} } }"; await TestAsync(text, "global::System.Boolean", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] ^ true; } }"; await TestAsync(text, "global::System.Boolean", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] ^ b ^ c && d; } }"; await TestAsync(text, "global::System.Boolean", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference3(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { var x = a ^ b ^ [|c|] && d; } }"; await TestAsync(text, "global::System.Boolean", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference4() { var text = @"using System; class C { static void Main(string[] args) { var x = Goo([|a|] ^ b); } static object Goo(Program p) { return p; } }"; await TestAsync(text, "Program", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference5(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { var x = Goo([|a|] ^ b); } static object Goo(bool p) { return p; } }"; await TestAsync(text, "global::System.Boolean", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference6() { var text = @"using System; class C { static void Main(string[] args) { if (([|x|] ^ y) != 0) {} } }"; await TestAsync(text, "global::System.Int32", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference7(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] ^ y) {} } }"; await TestAsync(text, "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrEqualsOperatorInference1(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] |= y) {} } }"; await TestAsync(text, "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrEqualsOperatorInference2(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { int z = [|x|] |= y; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndEqualsOperatorInference1(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] &= y) {} } }"; await TestAsync(text, "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndEqualsOperatorInference2(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { int z = [|x|] &= y; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorEqualsOperatorInference1(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] ^= y) {} } }"; await TestAsync(text, "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorEqualsOperatorInference2(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { int z = [|x|] ^= y; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInConstructor(TestMode mode) { await TestInClassAsync( @"C() { return [|Goo()|]; }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInDestructor(TestMode mode) { await TestInClassAsync( @"~C() { return [|Goo()|]; }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInMethod(TestMode mode) { await TestInClassAsync( @"int M() { return [|Goo()|]; }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInMethodNullableReference(TestMode mode) { await TestInClassAsync( @"#nullable enable string? M() { return [|Goo()|]; }", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInVoidMethod(TestMode mode) { await TestInClassAsync( @"void M() { return [|Goo()|]; }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskOfTMethod(TestMode mode) { await TestInClassAsync( @"async System.Threading.Tasks.Task<int> M() { return [|Goo()|]; }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskOfTMethodNestedNullability(TestMode mode) { await TestInClassAsync( @"async System.Threading.Tasks.Task<string?> M() { return [|Goo()|]; }", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskMethod(TestMode mode) { await TestInClassAsync( @"async System.Threading.Tasks.Task M() { return [|Goo()|]; }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncVoidMethod(TestMode mode) { await TestInClassAsync( @"async void M() { return [|Goo()|]; }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInOperator(TestMode mode) { await TestInClassAsync( @"public static C operator ++(C c) { return [|Goo()|]; }", "global::C", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInConversionOperator(TestMode mode) { await TestInClassAsync( @"public static implicit operator int(C c) { return [|Goo()|]; }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInPropertyGetter(TestMode mode) { await TestInClassAsync( @"int P { get { return [|Goo()|]; } }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInPropertyGetterNullableReference(TestMode mode) { await TestInClassAsync( @"#nullable enable string? P { get { return [|Goo()|]; } }", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInPropertySetter(TestMode mode) { await TestInClassAsync( @"int P { set { return [|Goo()|]; } }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInIndexerGetter(TestMode mode) { await TestInClassAsync( @"int this[int i] { get { return [|Goo()|]; } }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInIndexerGetterNullableReference(TestMode mode) { await TestInClassAsync( @"#nullable enable string? this[int i] { get { return [|Goo()|]; } }", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInIndexerSetter(TestMode mode) { await TestInClassAsync( @"int this[int i] { set { return [|Goo()|]; } }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInEventAdder(TestMode mode) { await TestInClassAsync( @"event System.EventHandler E { add { return [|Goo()|]; } remove { } }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInEventRemover(TestMode mode) { await TestInClassAsync( @"event System.EventHandler E { add { } remove { return [|Goo()|]; } }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInLocalFunction(TestMode mode) { await TestInClassAsync( @"void M() { int F() { return [|Goo()|]; } }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInLocalFunctionNullableReference(TestMode mode) { await TestInClassAsync( @"#nullable enable void M() { string? F() { return [|Goo()|]; } }", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskOfTLocalFunction(TestMode mode) { await TestInClassAsync( @"void M() { async System.Threading.Tasks.Task<int> F() { return [|Goo()|]; } }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskLocalFunction(TestMode mode) { await TestInClassAsync( @"void M() { async System.Threading.Tasks.Task F() { return [|Goo()|]; } }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncVoidLocalFunction(TestMode mode) { await TestInClassAsync( @"void M() { async void F() { return [|Goo()|]; } }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedConstructor(TestMode mode) { await TestInClassAsync( @"C() => [|Goo()|];", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedDestructor(TestMode mode) { await TestInClassAsync( @"~C() => [|Goo()|];", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedMethod(TestMode mode) { await TestInClassAsync( @"int M() => [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedVoidMethod(TestMode mode) { await TestInClassAsync( @"void M() => [|Goo()|];", "void", mode); } [WorkItem(27647, "https://github.com/dotnet/roslyn/issues/27647")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedAsyncTaskOfTMethod(TestMode mode) { await TestInClassAsync( @"async System.Threading.Tasks.Task<int> M() => [|Goo()|];", "global::System.Int32", mode); } [WorkItem(27647, "https://github.com/dotnet/roslyn/issues/27647")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedAsyncTaskOfTMethodNullableReference(TestMode mode) { await TestInClassAsync( @"#nullable enable async System.Threading.Tasks.Task<string?> M() => [|Goo()|];", "global::System.String?", mode); } [WorkItem(27647, "https://github.com/dotnet/roslyn/issues/27647")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedAsyncTaskMethod(TestMode mode) { await TestInClassAsync( @"async System.Threading.Tasks.Task M() => [|Goo()|];", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedAsyncVoidMethod(TestMode mode) { await TestInClassAsync( @"async void M() => [|Goo()|];", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedOperator(TestMode mode) { await TestInClassAsync( @"public static C operator ++(C c) => [|Goo()|];", "global::C", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedConversionOperator(TestMode mode) { await TestInClassAsync( @"public static implicit operator int(C c) => [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedProperty(TestMode mode) { await TestInClassAsync( @"int P => [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedIndexer(TestMode mode) { await TestInClassAsync( @"int this[int i] => [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedPropertyGetter(TestMode mode) { await TestInClassAsync( @"int P { get => [|Goo()|]; }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedPropertySetter(TestMode mode) { await TestInClassAsync( @"int P { set => [|Goo()|]; }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedIndexerGetter(TestMode mode) { await TestInClassAsync( @"int this[int i] { get => [|Goo()|]; }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedIndexerSetter(TestMode mode) { await TestInClassAsync( @"int this[int i] { set => [|Goo()|]; }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedEventAdder(TestMode mode) { await TestInClassAsync( @"event System.EventHandler E { add => [|Goo()|]; remove { } }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedEventRemover(TestMode mode) { await TestInClassAsync( @"event System.EventHandler E { add { } remove => [|Goo()|]; }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedLocalFunction(TestMode mode) { await TestInClassAsync( @"void M() { int F() => [|Goo()|]; }", "global::System.Int32", mode); } [WorkItem(27647, "https://github.com/dotnet/roslyn/issues/27647")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedAsyncTaskOfTLocalFunction(TestMode mode) { await TestInClassAsync( @"void M() { async System.Threading.Tasks.Task<int> F() => [|Goo()|]; }", "global::System.Int32", mode); } [WorkItem(27647, "https://github.com/dotnet/roslyn/issues/27647")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedAsyncTaskLocalFunction(TestMode mode) { await TestInClassAsync( @"void M() { async System.Threading.Tasks.Task F() => [|Goo()|]; }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedAsyncVoidLocalFunction(TestMode mode) { await TestInClassAsync( @"void M() { async void F() => [|Goo()|]; }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(827897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827897")] public async Task TestYieldReturnInMethod([CombinatorialValues("IEnumerable", "IEnumerator", "InvalidGenericType")] string returnTypeName, TestMode mode) { var markup = $@"using System.Collections.Generic; class C {{ {returnTypeName}<int> M() {{ yield return [|abc|] }} }}"; await TestAsync(markup, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestYieldReturnInMethodNullableReference([CombinatorialValues("IEnumerable", "IEnumerator", "InvalidGenericType")] string returnTypeName, TestMode mode) { var markup = $@"#nullable enable using System.Collections.Generic; class C {{ {returnTypeName}<string?> M() {{ yield return [|abc|] }} }}"; await TestAsync(markup, "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestYieldReturnInAsyncMethod([CombinatorialValues("IAsyncEnumerable", "IAsyncEnumerator", "InvalidGenericType")] string returnTypeName, TestMode mode) { var markup = $@"namespace System.Collections.Generic {{ interface {returnTypeName}<T> {{ }} class C {{ async {returnTypeName}<int> M() {{ yield return [|abc|] }} }} }}"; await TestAsync(markup, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestYieldReturnInvalidTypeInMethod([CombinatorialValues("int[]", "InvalidNonGenericType", "InvalidGenericType<int, int>")] string returnType, TestMode mode) { var markup = $@"class C {{ {returnType} M() {{ yield return [|abc|] }} }}"; await TestAsync(markup, "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(30235, "https://github.com/dotnet/roslyn/issues/30235")] public async Task TestYieldReturnInLocalFunction(TestMode mode) { var markup = @"using System.Collections.Generic; class C { void M() { IEnumerable<int> F() { yield return [|abc|] } } }"; await TestAsync(markup, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestYieldReturnInPropertyGetter(TestMode mode) { var markup = @"using System.Collections.Generic; class C { IEnumerable<int> P { get { yield return [|abc|] } } }"; await TestAsync(markup, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestYieldReturnInPropertySetter(TestMode mode) { var markup = @"using System.Collections.Generic; class C { IEnumerable<int> P { set { yield return [|abc|] } } }"; await TestAsync(markup, "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestYieldReturnAsGlobalStatement(TestMode mode) { await TestAsync( @"yield return [|abc|]", "global::System.Object", mode, sourceCodeKind: SourceCodeKind.Script); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInSimpleLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<string, int> f = s => { return [|Goo()|]; };", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInParenthesizedLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<int> f = () => { return [|Goo()|]; };", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInLambdaWithNullableReturn(TestMode mode) { await TestInMethodAsync( @"#nullable enable System.Func<string, string?> f = s => { return [|Goo()|]; };", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAnonymousMethod(TestMode mode) { await TestInMethodAsync( @"System.Func<int> f = delegate () { return [|Goo()|]; };", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAnonymousMethodWithNullableReturn(TestMode mode) { await TestInMethodAsync( @"#nullable enable System.Func<string?> f = delegate () { return [|Goo()|]; };", "global::System.String?", mode); } [WorkItem(4486, "https://github.com/dotnet/roslyn/issues/4486")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskOfTSimpleLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<string, System.Threading.Tasks.Task<int>> f = async s => { return [|Goo()|]; };", "global::System.Int32", mode); } [WorkItem(4486, "https://github.com/dotnet/roslyn/issues/4486")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskOfTParenthesizedLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<System.Threading.Tasks.Task<int>> f = async () => { return [|Goo()|]; };", "global::System.Int32", mode); } [WorkItem(4486, "https://github.com/dotnet/roslyn/issues/4486")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskOfTAnonymousMethod(TestMode mode) { await TestInMethodAsync( @"System.Func<System.Threading.Tasks.Task<int>> f = async delegate () { return [|Goo()|]; };", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskOfTAnonymousMethodWithNullableReference(TestMode mode) { await TestInMethodAsync( @"#nullable enable System.Func<System.Threading.Tasks.Task<string?>> f = async delegate () { return [|Goo()|]; };", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskSimpleLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<string, System.Threading.Tasks.Task> f = async s => { return [|Goo()|]; };", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskParenthesizedLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<System.Threading.Tasks.Task> f = async () => { return [|Goo()|]; };", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskAnonymousMethod(TestMode mode) { await TestInMethodAsync( @"System.Func<System.Threading.Tasks.Task> f = async delegate () { return [|Goo()|]; };", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncVoidSimpleLambda(TestMode mode) { await TestInMethodAsync( @"System.Action<string> f = async s => { return [|Goo()|]; };", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncVoidParenthesizedLambda(TestMode mode) { await TestInMethodAsync( @"System.Action f = async () => { return [|Goo()|]; };", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncVoidAnonymousMethod(TestMode mode) { await TestInMethodAsync( @"System.Action f = async delegate () { return [|Goo()|]; };", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnAsGlobalStatement(TestMode mode) { await TestAsync( @"return [|Goo()|];", "global::System.Object", mode, sourceCodeKind: SourceCodeKind.Script); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestSimpleLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<string, int> f = s => [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestParenthesizedLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<int> f = () => [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(30232, "https://github.com/dotnet/roslyn/issues/30232")] public async Task TestAsyncTaskOfTSimpleLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<string, System.Threading.Tasks.Task<int>> f = async s => [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestAsyncTaskOfTSimpleLambdaWithNullableReturn(TestMode mode) { await TestInMethodAsync( @"#nullable enable System.Func<string, System.Threading.Tasks.Task<string?>> f = async s => [|Goo()|];", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(30232, "https://github.com/dotnet/roslyn/issues/30232")] public async Task TestAsyncTaskOfTParenthesizedLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<System.Threading.Tasks.Task<int>> f = async () => [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(30232, "https://github.com/dotnet/roslyn/issues/30232")] public async Task TestAsyncTaskSimpleLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<string, System.Threading.Tasks.Task> f = async s => [|Goo()|];", "void", mode); } [WorkItem(30232, "https://github.com/dotnet/roslyn/issues/30232")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestAsyncTaskParenthesizedLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<System.Threading.Tasks.Task> f = async () => [|Goo()|];", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestAsyncVoidSimpleLambda(TestMode mode) { await TestInMethodAsync( @"System.Action<string> f = async s => [|Goo()|];", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestAsyncVoidParenthesizedLambda(TestMode mode) { await TestInMethodAsync( @"System.Action f = async () => [|Goo()|];", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionTreeSimpleLambda(TestMode mode) { await TestInMethodAsync( @"System.Linq.Expressions.Expression<System.Func<string, int>> f = s => [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionTreeParenthesizedLambda(TestMode mode) { await TestInMethodAsync( @"System.Linq.Expressions.Expression<System.Func<int>> f = () => [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestThrow(TestMode mode) { await TestInMethodAsync( @"throw [|Goo()|];", "global::System.Exception", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCatch(TestMode mode) => await TestInMethodAsync("try { } catch ([|Goo|] ex) { }", "global::System.Exception", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIf(TestMode mode) => await TestInMethodAsync(@"if ([|Goo()|]) { }", "global::System.Boolean", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestWhile(TestMode mode) => await TestInMethodAsync(@"while ([|Goo()|]) { }", "global::System.Boolean", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestDo(TestMode mode) => await TestInMethodAsync(@"do { } while ([|Goo()|])", "global::System.Boolean", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestFor1(TestMode mode) { await TestInMethodAsync( @"for (int i = 0; [|Goo()|]; i++) { }", "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestFor2(TestMode mode) => await TestInMethodAsync(@"for (string i = [|Goo()|]; ; ) { }", "global::System.String", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestFor3(TestMode mode) => await TestInMethodAsync(@"for (var i = [|Goo()|]; ; ) { }", "global::System.Int32", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestForNullableReference(TestMode mode) { await TestInMethodAsync( @"#nullable enable for (string? s = [|Goo()|]; ; ) { }", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestUsing1(TestMode mode) => await TestInMethodAsync(@"using ([|Goo()|]) { }", "global::System.IDisposable", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestUsing2(TestMode mode) => await TestInMethodAsync(@"using (int i = [|Goo()|]) { }", "global::System.Int32", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestUsing3(TestMode mode) => await TestInMethodAsync(@"using (var v = [|Goo()|]) { }", "global::System.IDisposable", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestForEach(TestMode mode) => await TestInMethodAsync(@"foreach (int v in [|Goo()|]) { }", "global::System.Collections.Generic.IEnumerable<global::System.Int32>", mode); [Theory(Skip = "https://github.com/dotnet/roslyn/issues/37309"), CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestForEachNullableElements(TestMode mode) { await TestInMethodAsync( @"#nullable enable foreach (string? v in [|Goo()|]) { }", "global::System.Collections.Generic.IEnumerable<global::System.String?>", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression1(TestMode mode) { await TestInMethodAsync( @"var q = +[|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression2(TestMode mode) { await TestInMethodAsync( @"var q = -[|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression3(TestMode mode) { await TestInMethodAsync( @"var q = ~[|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression4(TestMode mode) { await TestInMethodAsync( @"var q = ![|Goo()|];", "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression5(TestMode mode) { await TestInMethodAsync( @"var q = System.DayOfWeek.Monday & ~[|Goo()|];", "global::System.DayOfWeek", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayRankSpecifier(TestMode mode) { await TestInMethodAsync( @"var q = new string[[|Goo()|]];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestSwitch1(TestMode mode) => await TestInMethodAsync(@"switch ([|Goo()|]) { }", "global::System.Int32", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestSwitch2(TestMode mode) => await TestInMethodAsync(@"switch ([|Goo()|]) { default: }", "global::System.Int32", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestSwitch3(TestMode mode) => await TestInMethodAsync(@"switch ([|Goo()|]) { case ""a"": }", "global::System.String", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall1(TestMode mode) { await TestInMethodAsync( @"Bar([|Goo()|]);", "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall2(TestMode mode) { await TestInClassAsync( @"void M() { Bar([|Goo()|]); } void Bar(int i);", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall3(TestMode mode) { await TestInClassAsync( @"void M() { Bar([|Goo()|]); } void Bar();", "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall4(TestMode mode) { await TestInClassAsync( @"void M() { Bar([|Goo()|]); } void Bar(int i, string s);", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall5(TestMode mode) { await TestInClassAsync( @"void M() { Bar(s: [|Goo()|]); } void Bar(int i, string s);", "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCallNullableReference(TestMode mode) { await TestInClassAsync( @"void M() { Bar([|Goo()|]); } void Bar(string? s);", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall1(TestMode mode) { await TestInMethodAsync( @"new C([|Goo()|]);", "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall2(TestMode mode) { await TestInClassAsync( @"void M() { new C([|Goo()|]); } C(int i) { }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall3(TestMode mode) { await TestInClassAsync( @"void M() { new C([|Goo()|]); } C() { }", "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall4(TestMode mode) { await TestInClassAsync( @"void M() { new C([|Goo()|]); } C(int i, string s) { }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall5(TestMode mode) { await TestInClassAsync( @"void M() { new C(s: [|Goo()|]); } C(int i, string s) { }", "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCallNullableParameter(TestMode mode) { await TestInClassAsync( @"#nullable enable void M() { new C([|Goo()|]); } C(string? s) { }", "global::System.String?", mode); } [WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestThisConstructorInitializer1(TestMode mode) { await TestAsync( @"class MyClass { public MyClass(int x) : this([|test|]) { } }", "global::System.Int32", mode); } [WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestThisConstructorInitializer2(TestMode mode) { await TestAsync( @"class MyClass { public MyClass(int x, string y) : this(5, [|test|]) { } }", "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestThisConstructorInitializerNullableParameter(TestMode mode) { await TestAsync( @"#nullable enable class MyClass { public MyClass(string? y) : this([|test|]) { } }", "global::System.String?", mode); } [WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBaseConstructorInitializer(TestMode mode) { await TestAsync( @"class B { public B(int x) { } } class D : B { public D() : base([|test|]) { } }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBaseConstructorInitializerNullableParameter(TestMode mode) { await TestAsync( @"#nullable enable class B { public B(string? x) { } } class D : B { public D() : base([|test|]) { } }", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexAccess1(TestMode mode) { await TestInMethodAsync( @"string[] i; i[[|Goo()|]];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexerCall1(TestMode mode) => await TestInMethodAsync(@"this[[|Goo()|]];", "global::System.Int32", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexerCall2(TestMode mode) { await TestInClassAsync( @"void M() { this[[|Goo()|]]; } int this[long i] { get; }", "global::System.Int64", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexerCall3(TestMode mode) { await TestInClassAsync( @"void M() { this[42, [|Goo()|]]; } int this[int i, string s] { get; }", "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexerCall5(TestMode mode) { await TestInClassAsync( @"void M() { this[s: [|Goo()|]]; } int this[int i, string s] { get; }", "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInitializerInImplicitArrayCreationSimple(TestMode mode) { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { 1, [|2|] }; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInitializerInImplicitArrayCreation1(TestMode mode) { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Goo()|] }; } int Bar() { return 1; } int Goo() { return 2; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInitializerInImplicitArrayCreation2(TestMode mode) { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Goo()|] }; } int Bar() { return 1; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInitializerInImplicitArrayCreation3(TestMode mode) { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Goo()|] }; } }"; await TestAsync(text, "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInitializerInImplicitArrayCreationInferredAsNullable(TestMode mode) { var text = @"#nullable enable using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Goo()|] }; } object? Bar() { return null; } }"; await TestAsync(text, "global::System.Object?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInitializerInEqualsValueClauseSimple(TestMode mode) { var text = @"using System.Collections.Generic; class C { void M() { int[] a = { 1, [|2|] }; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInitializerInEqualsValueClause(TestMode mode) { var text = @"using System.Collections.Generic; class C { void M() { int[] a = { Bar(), [|Goo()|] }; } int Bar() { return 1; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInitializerInEqualsValueClauseNullableElement(TestMode mode) { var text = @"#nullable enable using System.Collections.Generic; class C { void M() { string?[] a = { [|Goo()|] }; } }"; await TestAsync(text, "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] public async Task TestCollectionInitializer1(TestMode mode) { var text = @"using System.Collections.Generic; class C { void M() { new List<int>() { [|Goo()|] }; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCollectionInitializerNullableElement(TestMode mode) { var text = @"#nullable enable using System.Collections.Generic; class C { void M() { new List<string?>() { [|Goo()|] }; } }"; await TestAsync(text, "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] public async Task TestCollectionInitializer2(TestMode mode) { var text = @" using System.Collections.Generic; class C { void M() { new Dictionary<int,string>() { { [|Goo()|], """" } }; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] public async Task TestCollectionInitializer3(TestMode mode) { var text = @" using System.Collections.Generic; class C { void M() { new Dictionary<int,string>() { { 0, [|Goo()|] } }; } }"; await TestAsync(text, "global::System.String", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] public async Task TestCustomCollectionInitializerAddMethod1() { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { [|a|] }; } void Add(int i) { } void Add(string s, bool b) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; await TestAsync(text, "global::System.Int32", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] public async Task TestCustomCollectionInitializerAddMethod2(TestMode mode) { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { { ""test"", [|b|] } }; } void Add(int i) { } void Add(string s, bool b) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; await TestAsync(text, "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] public async Task TestCustomCollectionInitializerAddMethod3(TestMode mode) { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { { [|s|], true } }; } void Add(int i) { } void Add(string s, bool b) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; await TestAsync(text, "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCustomCollectionInitializerAddMethodWithNullableParameter(TestMode mode) { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { { ""test"", [|s|] } }; } void Add(int i) { } void Add(string s, string? s2) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; await TestAsync(text, "global::System.String?", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference1() { var text = @" class A { void Goo() { A[] x = new [|C|][] { }; } }"; await TestAsync(text, "global::A", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference1_Position() { var text = @" class A { void Goo() { A[] x = new [|C|][] { }; } }"; await TestAsync(text, "global::A[]", TestMode.Position); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference2() { var text = @" class A { void Goo() { A[][] x = new [|C|][][] { }; } }"; await TestAsync(text, "global::A", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference2_Position() { var text = @" class A { void Goo() { A[][] x = new [|C|][][] { }; } }"; await TestAsync(text, "global::A[][]", TestMode.Position); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference3() { var text = @" class A { void Goo() { A[][] x = new [|C|][] { }; } }"; await TestAsync(text, "global::A[]", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference3_Position() { var text = @" class A { void Goo() { A[][] x = new [|C|][] { }; } }"; await TestAsync(text, "global::A[][]", TestMode.Position); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference4(TestMode mode) { var text = @" using System; class A { void Goo() { Func<int, int>[] x = new Func<int, int>[] { [|Bar()|] }; } }"; await TestAsync(text, "global::System.Func<global::System.Int32, global::System.Int32>", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(538993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538993")] public async Task TestInsideLambda2(TestMode mode) { var text = @"using System; class C { void M() { Func<int,int> f = i => [|here|] } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestInsideLambdaNullableReturn(TestMode mode) { var text = @"#nullable enable using System; class C { void M() { Func<int, string?> f = i => [|here|] } }"; await TestAsync(text, "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(539813, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539813")] public async Task TestPointer1(TestMode mode) { var text = @"class C { void M(int* i) { var q = i[[|Goo()|]]; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(539813, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539813")] public async Task TestDynamic1(TestMode mode) { var text = @"class C { void M(dynamic i) { var q = i[[|Goo()|]]; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestChecked1(TestMode mode) { var text = @"class C { void M() { string q = checked([|Goo()|]); } }"; await TestAsync(text, "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(553584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553584")] public async Task TestAwaitTaskOfT(TestMode mode) { var text = @"using System.Threading.Tasks; class C { void M() { int x = await [|Goo()|]; } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Int32>", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestAwaitTaskOfTNullableValue(TestMode mode) { var text = @"#nullable enable using System.Threading.Tasks; class C { void M() { string? x = await [|Goo()|]; } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.String?>", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(553584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553584")] public async Task TestAwaitTaskOfTaskOfT(TestMode mode) { var text = @"using System.Threading.Tasks; class C { void M() { Task<int> x = await [|Goo()|]; } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Threading.Tasks.Task<global::System.Int32>>", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(553584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553584")] public async Task TestAwaitTask(TestMode mode) { var text = @"using System.Threading.Tasks; class C { void M() { await [|Goo()|]; } }"; await TestAsync(text, "global::System.Threading.Tasks.Task", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617622")] public async Task TestLockStatement(TestMode mode) { var text = @"class C { void M() { lock([|Goo()|]) { } } }"; await TestAsync(text, "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617622")] public async Task TestAwaitExpressionInLockStatement(TestMode mode) { var text = @"class C { async void M() { lock(await [|Goo()|]) { } } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Object>", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(827897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827897")] public async Task TestReturnFromAsyncTaskOfT(TestMode mode) { var markup = @"using System.Threading.Tasks; class Program { async Task<int> M() { await Task.Delay(1); return [|ab|] } }"; await TestAsync(markup, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(853840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853840")] public async Task TestAttributeArguments1(TestMode mode) { var markup = @"[A([|dd|], ee, Y = ff)] class AAttribute : System.Attribute { public int X; public string Y; public AAttribute(System.DayOfWeek a, double b) { } }"; await TestAsync(markup, "global::System.DayOfWeek", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(853840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853840")] public async Task TestAttributeArguments2(TestMode mode) { var markup = @"[A(dd, [|ee|], Y = ff)] class AAttribute : System.Attribute { public int X; public string Y; public AAttribute(System.DayOfWeek a, double b) { } }"; await TestAsync(markup, "global::System.Double", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(853840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853840")] public async Task TestAttributeArguments3(TestMode mode) { var markup = @"[A(dd, ee, Y = [|ff|])] class AAttribute : System.Attribute { public int X; public string Y; public AAttribute(System.DayOfWeek a, double b) { } }"; await TestAsync(markup, "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(757111, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/757111")] public async Task TestReturnStatementWithinDelegateWithinAMethodCall(TestMode mode) { var text = @"using System; class Program { delegate string A(int i); static void Main(string[] args) { B(delegate(int i) { return [|M()|]; }); } private static void B(A a) { } }"; await TestAsync(text, "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(994388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994388")] public async Task TestCatchFilterClause(TestMode mode) { var text = @" try { } catch (Exception) if ([|M()|]) }"; await TestInMethodAsync(text, "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(994388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994388")] public async Task TestCatchFilterClause1(TestMode mode) { var text = @" try { } catch (Exception) if ([|M|]) }"; await TestInMethodAsync(text, "global::System.Boolean", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(994388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994388")] public async Task TestCatchFilterClause2() { var text = @" try { } catch (Exception) if ([|M|].N) }"; await TestInMethodAsync(text, "global::System.Object", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")] public async Task TestAwaitExpressionWithChainingMethod() { var text = @"using System; using System.Threading.Tasks; class C { static async void T() { bool x = await [|M()|].ConfigureAwait(false); } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Boolean>", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")] public async Task TestAwaitExpressionWithChainingMethod2() { var text = @"using System; using System.Threading.Tasks; class C { static async void T() { bool x = await [|M|].ContinueWith(a => { return true; }).ContinueWith(a => { return false; }); } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Object>", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4233, "https://github.com/dotnet/roslyn/issues/4233")] public async Task TestAwaitExpressionWithGenericMethod1() { var text = @"using System.Threading.Tasks; public class C { private async void M() { bool merged = await X([|Test()|]); } private async Task<T> X<T>(T t) { return t; } }"; await TestAsync(text, "global::System.Boolean", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4233, "https://github.com/dotnet/roslyn/issues/4233")] public async Task TestAwaitExpressionWithGenericMethod2(TestMode mode) { var text = @"using System.Threading.Tasks; public class C { private async void M() { bool merged = await Task.Run(() => [|Test()|]);; } private async Task<T> X<T>(T t) { return t; } }"; await TestAsync(text, "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")] public async Task TestNullCoalescingOperator1(TestMode mode) { var text = @"class C { void M() { object z = [|a|] ?? null; } }"; // In position mode, we are inferring that the thing to the right is an object, because it's being assigned to a local of type object. // In node mode, we are inferring the node is an object? because it's to the left of the ??. await TestAsync(text, mode == TestMode.Node ? "global::System.Object?" : "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")] public async Task TestNullCoalescingOperator2(TestMode mode) { var text = @"class C { void M() { object z = [|a|] ?? b ?? c; } }"; // In position mode, we are inferring that the thing to the right is an object, because it's being assigned to a local of type object. // In node mode, we are inferring the node is an object? because it's to the left of the ??. await TestAsync(text, mode == TestMode.Node ? "global::System.Object?" : "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")] public async Task TestNullCoalescingOperator3(TestMode mode) { var text = @"class C { void M() { object z = a ?? [|b|] ?? c; } }"; // In position mode, we are inferring that the thing to the right is an object, because it's to the right of the first ?? // and thus must be the same type as the object being assigned to. // In node mode, we are inferring the node is an object? because it's to the left of the ??. await TestAsync(text, mode == TestMode.Node ? "global::System.Object?" : "global::System.Object", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(5126, "https://github.com/dotnet/roslyn/issues/5126")] public async Task TestSelectLambda() { var text = @"using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<string> args) { args = args.Select(a =>[||]) } }"; await TestAsync(text, "global::System.Object", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(5126, "https://github.com/dotnet/roslyn/issues/5126")] public async Task TestSelectLambda2() { var text = @"using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<string> args) { args = args.Select(a =>[|b|]) } }"; await TestAsync(text, "global::System.String", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(1903, "https://github.com/dotnet/roslyn/issues/1903")] public async Task TestSelectLambda3(TestMode mode) { var text = @"using System.Collections.Generic; using System.Linq; class A { } class B { } class C { IEnumerable<B> GetB(IEnumerable<A> a) { return a.Select(i => [|Goo(i)|]); } }"; await TestAsync(text, "global::B", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(6765, "https://github.com/dotnet/roslyn/issues/6765")] public async Task TestDefaultStatement1() { var text = @"class C { static void Main(string[] args) { System.ConsoleModifiers c = default([||]) } }"; await TestAsync(text, "global::System.ConsoleModifiers", TestMode.Position); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(6765, "https://github.com/dotnet/roslyn/issues/6765")] public async Task TestDefaultStatement2() { var text = @"class C { static void Goo(System.ConsoleModifiers arg) { Goo(default([||]) } }"; await TestAsync(text, "global::System.ConsoleModifiers", TestMode.Position); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestWhereCall() { var text = @" using System.Collections.Generic; class C { void Goo() { [|ints|].Where(i => i > 10); } }"; await TestAsync(text, "global::System.Collections.Generic.IEnumerable<global::System.Int32>", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestWhereCall2() { var text = @" using System.Collections.Generic; class C { void Goo() { [|ints|].Where(i => null); } }"; await TestAsync(text, "global::System.Collections.Generic.IEnumerable<global::System.Object>", TestMode.Node); } [WorkItem(12755, "https://github.com/dotnet/roslyn/issues/12755")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestObjectCreationBeforeArrayIndexing() { var text = @"using System; class C { void M() { int[] array; C p = new [||] array[4] = 4; } }"; await TestAsync(text, "global::C", TestMode.Position); } [WorkItem(15468, "https://github.com/dotnet/roslyn/issues/15468")] [WorkItem(25305, "https://github.com/dotnet/roslyn/issues/25305")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestDeconstruction() { await TestInMethodAsync( @"[|(int i, _)|] =", "(global::System.Int32 i, global::System.Object _)", TestMode.Node); } [WorkItem(15468, "https://github.com/dotnet/roslyn/issues/15468")] [WorkItem(25305, "https://github.com/dotnet/roslyn/issues/25305")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestDeconstruction2() { await TestInMethodAsync( @"(int i, _) = [||]", "(global::System.Int32 i, global::System.Object _)", TestMode.Position); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestDeconstructionWithNullableElement() { await TestInMethodAsync( @"[|(string? s, _)|] =", "(global::System.String? s, global::System.Object _)", TestMode.Node); } [WorkItem(13402, "https://github.com/dotnet/roslyn/issues/13402")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestObjectCreationBeforeBlock() { var text = @"class Program { static void Main(string[] args) { Program p = new [||] { } } }"; await TestAsync(text, "global::Program", TestMode.Position); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestInferringThroughGenericFunctionWithNullableReturn(TestMode mode) { var text = @"#nullable enable class Program { static void Main(string[] args) { string? s = Identity([|input|]); } static T Identity<T>(T value) { return value; } }"; await TestAsync(text, "global::System.String?", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestInferringThroughGenericFunctionMissingArgument() { var text = @"class Program { static void Main(string[] args) { string s = Identity([||]); } static T Identity<T>(T value) { return value; } }"; await TestAsync(text, "global::System.String", TestMode.Position); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestInferringThroughGenericFunctionTooManyArguments(TestMode mode) { var text = @"class Program { static void Main(string[] args) { string s = Identity(""test"", [||]); } static T Identity<T>(T value) { return value; } }"; await TestAsync(text, "global::System.Object", mode); } [WorkItem(14277, "https://github.com/dotnet/roslyn/issues/14277")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestValueInNestedTuple1(TestMode mode) { await TestInMethodAsync( @"(int, (string, bool)) x = ([|Goo()|], ("""", true));", "global::System.Int32", mode); } [WorkItem(14277, "https://github.com/dotnet/roslyn/issues/14277")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestValueInNestedTuple2(TestMode mode) { await TestInMethodAsync( @"(int, (string, bool)) x = (1, ("""", [|Goo()|]));", "global::System.Boolean", mode); } [WorkItem(14277, "https://github.com/dotnet/roslyn/issues/14277")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestValueInNestedTuple3() { await TestInMethodAsync( @"(int, string) x = (1, [||]);", "global::System.String", TestMode.Position); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestInferringInEnumHasFlags(TestMode mode) { var text = @"using System.IO; class Program { static void Main(string[] args) { FileInfo f; f.Attributes.HasFlag([|flag|]); } }"; await TestAsync(text, "global::System.IO.FileAttributes", mode); } [Theory] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [InlineData("")] [InlineData("Re")] [InlineData("Col")] [InlineData("Color.Green or", false)] [InlineData("Color.Green or ")] [InlineData("(Color.Green or ")] // start of: is (Color.Red or Color.Green) and not Color.Blue [InlineData("Color.Green or Re")] [InlineData("Color.Green or Color.Red or ")] [InlineData("Color.Green orWrittenWrong ", false)] [InlineData("not ")] [InlineData("not Re")] public async Task TestEnumInPatterns_Is_ConstUnaryAndBinaryPattern(string isPattern, bool shouldInferColor = true) { var markup = @$" class C {{ public enum Color {{ Red, Green, }} public void M(Color c) {{ var isRed = c is {isPattern}[||]; }} }} "; var expectedType = shouldInferColor ? "global::C.Color" : "global::System.Object"; await TestAsync(markup, expectedType, TestMode.Position); } [Theory] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [InlineData("")] [InlineData("Col")] [InlineData("Color.R")] [InlineData("Red")] [InlineData("Color.Green or ")] [InlineData("Color.Green or Re")] [InlineData("not ")] [InlineData("not Re")] public async Task TestEnumInPatterns_Is_PropertyPattern(string partialWritten) { var markup = @$" public enum Color {{ Red, Green, }} class C {{ public Color Color {{ get; }} public void M() {{ var isRed = this is {{ Color: {partialWritten}[||] }} }} "; await TestAsync(markup, "global::Color", TestMode.Position); } [Fact] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestEnumInPatterns_SwitchStatement_PropertyPattern() { var markup = @" public enum Color { Red, Green, } class C { public Color Color { get; } public void M() { switch (this) { case { Color: [||] } } "; await TestAsync(markup, "global::Color", TestMode.Position); } [Fact] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestEnumInPatterns_SwitchExpression_PropertyPattern() { var markup = @" public enum Color { Red, Green, } class C { public Color Color { get; } public void M() { var isRed = this switch { { Color: [||] } } "; await TestAsync(markup, "global::Color", TestMode.Position); } [Fact] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestEnumInPatterns_SwitchStatement_ExtendedPropertyPattern() { var markup = @" public enum Color { Red, Green, } class C { public C AnotherC { get; } public Color Color { get; } public void M() { switch (this) { case { AnotherC.Color: [||] } } "; await TestAsync(markup, "global::Color", TestMode.Position); } [Fact] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestEnumInPatterns_SwitchStatement_ExtendedPropertyPattern_Field() { var markup = @" public enum Color { Red, Green, } class C { public C AnotherC { get; } public Color Color; public void M() { switch (this) { case { AnotherC.Color: [||] } } "; await TestAsync(markup, "global::Color", TestMode.Position); } } }
// Licensed to the .NET Foundation under one or more 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 System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.TypeInferrer; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.TypeInferrer { public partial class TypeInferrerTests : TypeInferrerTestBase<CSharpTestWorkspaceFixture> { protected override async Task TestWorkerAsync(Document document, TextSpan textSpan, string expectedType, TestMode mode) { var root = await document.GetSyntaxRootAsync(); var node = FindExpressionSyntaxFromSpan(root, textSpan); var typeInference = document.GetLanguageService<ITypeInferenceService>(); ITypeSymbol inferredType; if (mode == TestMode.Position) { var position = node?.SpanStart ?? textSpan.Start; inferredType = typeInference.InferType(await document.ReuseExistingSpeculativeModelAsync(position, CancellationToken.None), position, objectAsDefault: true, cancellationToken: CancellationToken.None); } else { inferredType = typeInference.InferType(await document.ReuseExistingSpeculativeModelAsync(node?.Span ?? textSpan, CancellationToken.None), node, objectAsDefault: true, cancellationToken: CancellationToken.None); } var typeSyntax = inferredType.GenerateTypeSyntax().NormalizeWhitespace(); Assert.Equal(expectedType, typeSyntax.ToString()); } private async Task TestInClassAsync(string text, string expectedType, TestMode mode) { text = @"class C { $ }".Replace("$", text); await TestAsync(text, expectedType, mode); } private async Task TestInMethodAsync(string text, string expectedType, TestMode mode) { text = @"class C { void M() { $ } }".Replace("$", text); await TestAsync(text, expectedType, mode); } private static ExpressionSyntax FindExpressionSyntaxFromSpan(SyntaxNode root, TextSpan textSpan) { var token = root.FindToken(textSpan.Start); var currentNode = token.Parent; while (currentNode != null) { if (currentNode is ExpressionSyntax result && result.Span == textSpan) { return result; } currentNode = currentNode.Parent; } return null; } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConditional1() { // We do not support position inference here as we're before the ? and we only look // backwards to infer a type here. await TestInMethodAsync( @"var q = [|Goo()|] ? 1 : 2;", "global::System.Boolean", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConditional2(TestMode mode) { await TestInMethodAsync( @"var q = a ? [|Goo()|] : 2;", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConditional3(TestMode mode) { await TestInMethodAsync( @"var q = a ? """" : [|Goo()|];", "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestVariableDeclarator1(TestMode mode) { await TestInMethodAsync( @"int q = [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestVariableDeclarator2(TestMode mode) { await TestInMethodAsync( @"var q = [|Goo()|];", "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestVariableDeclaratorNullableReferenceType(TestMode mode) { await TestInMethodAsync( @"#nullable enable string? q = [|Goo()|];", "global::System.String?", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesce1() { await TestInMethodAsync( @"var q = [|Goo()|] ?? 1;", "global::System.Int32?", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesce2(TestMode mode) { await TestInMethodAsync( @"bool? b; var q = b ?? [|Goo()|];", "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesce3(TestMode mode) { await TestInMethodAsync( @"string s; var q = s ?? [|Goo()|];", "global::System.String", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesce4() { await TestInMethodAsync( @"var q = [|Goo()|] ?? string.Empty;", "global::System.String?", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesceWithErrorType() { // We could be smart and infer this as an ErrorType?, but in the #nullable disable case we don't know if this is intended to be // a struct (where the question mark is legal) or a class (where it isn't). We'll thus avoid sticking question marks in this case. // https://github.com/dotnet/roslyn/issues/37852 tracks fixing this is a much fancier way. await TestInMethodAsync( @"ErrorType s; var q = [|Goo()|] ?? s;", "ErrorType", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBinaryExpression1(TestMode mode) { await TestInMethodAsync( @"string s; var q = s + [|Goo()|];", "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBinaryExpression2(TestMode mode) { await TestInMethodAsync( @"var s; var q = s || [|Goo()|];", "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBinaryOperator1(TestMode mode) { await TestInMethodAsync( @"var q = x << [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBinaryOperator2(TestMode mode) { await TestInMethodAsync( @"var q = x >> [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestAssignmentOperator3(TestMode mode) { await TestInMethodAsync( @"var q <<= [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestAssignmentOperator4(TestMode mode) { await TestInMethodAsync( @"var q >>= [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestOverloadedConditionalLogicalOperatorsInferBool(TestMode mode) { await TestAsync( @"using System; class C { public static C operator &(C c, C d) { return null; } public static bool operator true(C c) { return true; } public static bool operator false(C c) { return false; } static void Main(string[] args) { var c = new C() && [|Goo()|]; } }", "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestConditionalLogicalOrOperatorAlwaysInfersBool(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { var x = a || [|7|]; } }"; await TestAsync(text, "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestConditionalLogicalAndOperatorAlwaysInfersBool(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { var x = a && [|7|]; } }"; await TestAsync(text, "global::System.Boolean", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] | true; } }"; await TestAsync(text, "global::System.Boolean", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] | b | c || d; } }"; await TestAsync(text, "global::System.Boolean", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference3(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { var x = a | b | [|c|] || d; } }"; await TestAsync(text, "global::System.Boolean", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference4() { var text = @"using System; class C { static void Main(string[] args) { var x = Goo([|a|] | b); } static object Goo(Program p) { return p; } }"; await TestAsync(text, "Program", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference5(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { var x = Goo([|a|] | b); } static object Goo(bool p) { return p; } }"; await TestAsync(text, "global::System.Boolean", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference6() { var text = @"using System; class C { static void Main(string[] args) { if (([|x|] | y) != 0) {} } }"; await TestAsync(text, "global::System.Int32", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference7(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] | y) {} } }"; await TestAsync(text, "global::System.Boolean", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] & true; } }"; await TestAsync(text, "global::System.Boolean", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] & b & c && d; } }"; await TestAsync(text, "global::System.Boolean", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference3(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { var x = a & b & [|c|] && d; } }"; await TestAsync(text, "global::System.Boolean", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference4() { var text = @"using System; class C { static void Main(string[] args) { var x = Goo([|a|] & b); } static object Goo(Program p) { return p; } }"; await TestAsync(text, "Program", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference5(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { var x = Goo([|a|] & b); } static object Goo(bool p) { return p; } }"; await TestAsync(text, "global::System.Boolean", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference6() { var text = @"using System; class C { static void Main(string[] args) { if (([|x|] & y) != 0) {} } }"; await TestAsync(text, "global::System.Int32", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference7(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] & y) {} } }"; await TestAsync(text, "global::System.Boolean", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] ^ true; } }"; await TestAsync(text, "global::System.Boolean", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] ^ b ^ c && d; } }"; await TestAsync(text, "global::System.Boolean", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference3(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { var x = a ^ b ^ [|c|] && d; } }"; await TestAsync(text, "global::System.Boolean", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference4() { var text = @"using System; class C { static void Main(string[] args) { var x = Goo([|a|] ^ b); } static object Goo(Program p) { return p; } }"; await TestAsync(text, "Program", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference5(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { var x = Goo([|a|] ^ b); } static object Goo(bool p) { return p; } }"; await TestAsync(text, "global::System.Boolean", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference6() { var text = @"using System; class C { static void Main(string[] args) { if (([|x|] ^ y) != 0) {} } }"; await TestAsync(text, "global::System.Int32", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference7(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] ^ y) {} } }"; await TestAsync(text, "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrEqualsOperatorInference1(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] |= y) {} } }"; await TestAsync(text, "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrEqualsOperatorInference2(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { int z = [|x|] |= y; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndEqualsOperatorInference1(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] &= y) {} } }"; await TestAsync(text, "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndEqualsOperatorInference2(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { int z = [|x|] &= y; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorEqualsOperatorInference1(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] ^= y) {} } }"; await TestAsync(text, "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorEqualsOperatorInference2(TestMode mode) { var text = @"using System; class C { static void Main(string[] args) { int z = [|x|] ^= y; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInConstructor(TestMode mode) { await TestInClassAsync( @"C() { return [|Goo()|]; }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInDestructor(TestMode mode) { await TestInClassAsync( @"~C() { return [|Goo()|]; }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInMethod(TestMode mode) { await TestInClassAsync( @"int M() { return [|Goo()|]; }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInMethodNullableReference(TestMode mode) { await TestInClassAsync( @"#nullable enable string? M() { return [|Goo()|]; }", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInVoidMethod(TestMode mode) { await TestInClassAsync( @"void M() { return [|Goo()|]; }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskOfTMethod(TestMode mode) { await TestInClassAsync( @"async System.Threading.Tasks.Task<int> M() { return [|Goo()|]; }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskOfTMethodNestedNullability(TestMode mode) { await TestInClassAsync( @"async System.Threading.Tasks.Task<string?> M() { return [|Goo()|]; }", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskMethod(TestMode mode) { await TestInClassAsync( @"async System.Threading.Tasks.Task M() { return [|Goo()|]; }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncVoidMethod(TestMode mode) { await TestInClassAsync( @"async void M() { return [|Goo()|]; }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInOperator(TestMode mode) { await TestInClassAsync( @"public static C operator ++(C c) { return [|Goo()|]; }", "global::C", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInConversionOperator(TestMode mode) { await TestInClassAsync( @"public static implicit operator int(C c) { return [|Goo()|]; }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInPropertyGetter(TestMode mode) { await TestInClassAsync( @"int P { get { return [|Goo()|]; } }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInPropertyGetterNullableReference(TestMode mode) { await TestInClassAsync( @"#nullable enable string? P { get { return [|Goo()|]; } }", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInPropertySetter(TestMode mode) { await TestInClassAsync( @"int P { set { return [|Goo()|]; } }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInIndexerGetter(TestMode mode) { await TestInClassAsync( @"int this[int i] { get { return [|Goo()|]; } }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInIndexerGetterNullableReference(TestMode mode) { await TestInClassAsync( @"#nullable enable string? this[int i] { get { return [|Goo()|]; } }", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInIndexerSetter(TestMode mode) { await TestInClassAsync( @"int this[int i] { set { return [|Goo()|]; } }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInEventAdder(TestMode mode) { await TestInClassAsync( @"event System.EventHandler E { add { return [|Goo()|]; } remove { } }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInEventRemover(TestMode mode) { await TestInClassAsync( @"event System.EventHandler E { add { } remove { return [|Goo()|]; } }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInLocalFunction(TestMode mode) { await TestInClassAsync( @"void M() { int F() { return [|Goo()|]; } }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInLocalFunctionNullableReference(TestMode mode) { await TestInClassAsync( @"#nullable enable void M() { string? F() { return [|Goo()|]; } }", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskOfTLocalFunction(TestMode mode) { await TestInClassAsync( @"void M() { async System.Threading.Tasks.Task<int> F() { return [|Goo()|]; } }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskLocalFunction(TestMode mode) { await TestInClassAsync( @"void M() { async System.Threading.Tasks.Task F() { return [|Goo()|]; } }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncVoidLocalFunction(TestMode mode) { await TestInClassAsync( @"void M() { async void F() { return [|Goo()|]; } }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedConstructor(TestMode mode) { await TestInClassAsync( @"C() => [|Goo()|];", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedDestructor(TestMode mode) { await TestInClassAsync( @"~C() => [|Goo()|];", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedMethod(TestMode mode) { await TestInClassAsync( @"int M() => [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedVoidMethod(TestMode mode) { await TestInClassAsync( @"void M() => [|Goo()|];", "void", mode); } [WorkItem(27647, "https://github.com/dotnet/roslyn/issues/27647")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedAsyncTaskOfTMethod(TestMode mode) { await TestInClassAsync( @"async System.Threading.Tasks.Task<int> M() => [|Goo()|];", "global::System.Int32", mode); } [WorkItem(27647, "https://github.com/dotnet/roslyn/issues/27647")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedAsyncTaskOfTMethodNullableReference(TestMode mode) { await TestInClassAsync( @"#nullable enable async System.Threading.Tasks.Task<string?> M() => [|Goo()|];", "global::System.String?", mode); } [WorkItem(27647, "https://github.com/dotnet/roslyn/issues/27647")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedAsyncTaskMethod(TestMode mode) { await TestInClassAsync( @"async System.Threading.Tasks.Task M() => [|Goo()|];", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedAsyncVoidMethod(TestMode mode) { await TestInClassAsync( @"async void M() => [|Goo()|];", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedOperator(TestMode mode) { await TestInClassAsync( @"public static C operator ++(C c) => [|Goo()|];", "global::C", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedConversionOperator(TestMode mode) { await TestInClassAsync( @"public static implicit operator int(C c) => [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedProperty(TestMode mode) { await TestInClassAsync( @"int P => [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedIndexer(TestMode mode) { await TestInClassAsync( @"int this[int i] => [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedPropertyGetter(TestMode mode) { await TestInClassAsync( @"int P { get => [|Goo()|]; }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedPropertySetter(TestMode mode) { await TestInClassAsync( @"int P { set => [|Goo()|]; }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedIndexerGetter(TestMode mode) { await TestInClassAsync( @"int this[int i] { get => [|Goo()|]; }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedIndexerSetter(TestMode mode) { await TestInClassAsync( @"int this[int i] { set => [|Goo()|]; }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedEventAdder(TestMode mode) { await TestInClassAsync( @"event System.EventHandler E { add => [|Goo()|]; remove { } }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedEventRemover(TestMode mode) { await TestInClassAsync( @"event System.EventHandler E { add { } remove => [|Goo()|]; }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedLocalFunction(TestMode mode) { await TestInClassAsync( @"void M() { int F() => [|Goo()|]; }", "global::System.Int32", mode); } [WorkItem(27647, "https://github.com/dotnet/roslyn/issues/27647")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedAsyncTaskOfTLocalFunction(TestMode mode) { await TestInClassAsync( @"void M() { async System.Threading.Tasks.Task<int> F() => [|Goo()|]; }", "global::System.Int32", mode); } [WorkItem(27647, "https://github.com/dotnet/roslyn/issues/27647")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedAsyncTaskLocalFunction(TestMode mode) { await TestInClassAsync( @"void M() { async System.Threading.Tasks.Task F() => [|Goo()|]; }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionBodiedAsyncVoidLocalFunction(TestMode mode) { await TestInClassAsync( @"void M() { async void F() => [|Goo()|]; }", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(827897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827897")] public async Task TestYieldReturnInMethod([CombinatorialValues("IEnumerable", "IEnumerator", "InvalidGenericType")] string returnTypeName, TestMode mode) { var markup = $@"using System.Collections.Generic; class C {{ {returnTypeName}<int> M() {{ yield return [|abc|] }} }}"; await TestAsync(markup, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestYieldReturnInMethodNullableReference([CombinatorialValues("IEnumerable", "IEnumerator", "InvalidGenericType")] string returnTypeName, TestMode mode) { var markup = $@"#nullable enable using System.Collections.Generic; class C {{ {returnTypeName}<string?> M() {{ yield return [|abc|] }} }}"; await TestAsync(markup, "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestYieldReturnInAsyncMethod([CombinatorialValues("IAsyncEnumerable", "IAsyncEnumerator", "InvalidGenericType")] string returnTypeName, TestMode mode) { var markup = $@"namespace System.Collections.Generic {{ interface {returnTypeName}<T> {{ }} class C {{ async {returnTypeName}<int> M() {{ yield return [|abc|] }} }} }}"; await TestAsync(markup, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestYieldReturnInvalidTypeInMethod([CombinatorialValues("int[]", "InvalidNonGenericType", "InvalidGenericType<int, int>")] string returnType, TestMode mode) { var markup = $@"class C {{ {returnType} M() {{ yield return [|abc|] }} }}"; await TestAsync(markup, "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(30235, "https://github.com/dotnet/roslyn/issues/30235")] public async Task TestYieldReturnInLocalFunction(TestMode mode) { var markup = @"using System.Collections.Generic; class C { void M() { IEnumerable<int> F() { yield return [|abc|] } } }"; await TestAsync(markup, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestYieldReturnInPropertyGetter(TestMode mode) { var markup = @"using System.Collections.Generic; class C { IEnumerable<int> P { get { yield return [|abc|] } } }"; await TestAsync(markup, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestYieldReturnInPropertySetter(TestMode mode) { var markup = @"using System.Collections.Generic; class C { IEnumerable<int> P { set { yield return [|abc|] } } }"; await TestAsync(markup, "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestYieldReturnAsGlobalStatement(TestMode mode) { await TestAsync( @"yield return [|abc|]", "global::System.Object", mode, sourceCodeKind: SourceCodeKind.Script); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInSimpleLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<string, int> f = s => { return [|Goo()|]; };", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInParenthesizedLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<int> f = () => { return [|Goo()|]; };", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInLambdaWithNullableReturn(TestMode mode) { await TestInMethodAsync( @"#nullable enable System.Func<string, string?> f = s => { return [|Goo()|]; };", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAnonymousMethod(TestMode mode) { await TestInMethodAsync( @"System.Func<int> f = delegate () { return [|Goo()|]; };", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAnonymousMethodWithNullableReturn(TestMode mode) { await TestInMethodAsync( @"#nullable enable System.Func<string?> f = delegate () { return [|Goo()|]; };", "global::System.String?", mode); } [WorkItem(4486, "https://github.com/dotnet/roslyn/issues/4486")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskOfTSimpleLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<string, System.Threading.Tasks.Task<int>> f = async s => { return [|Goo()|]; };", "global::System.Int32", mode); } [WorkItem(4486, "https://github.com/dotnet/roslyn/issues/4486")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskOfTParenthesizedLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<System.Threading.Tasks.Task<int>> f = async () => { return [|Goo()|]; };", "global::System.Int32", mode); } [WorkItem(4486, "https://github.com/dotnet/roslyn/issues/4486")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskOfTAnonymousMethod(TestMode mode) { await TestInMethodAsync( @"System.Func<System.Threading.Tasks.Task<int>> f = async delegate () { return [|Goo()|]; };", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskOfTAnonymousMethodWithNullableReference(TestMode mode) { await TestInMethodAsync( @"#nullable enable System.Func<System.Threading.Tasks.Task<string?>> f = async delegate () { return [|Goo()|]; };", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskSimpleLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<string, System.Threading.Tasks.Task> f = async s => { return [|Goo()|]; };", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskParenthesizedLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<System.Threading.Tasks.Task> f = async () => { return [|Goo()|]; };", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncTaskAnonymousMethod(TestMode mode) { await TestInMethodAsync( @"System.Func<System.Threading.Tasks.Task> f = async delegate () { return [|Goo()|]; };", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncVoidSimpleLambda(TestMode mode) { await TestInMethodAsync( @"System.Action<string> f = async s => { return [|Goo()|]; };", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncVoidParenthesizedLambda(TestMode mode) { await TestInMethodAsync( @"System.Action f = async () => { return [|Goo()|]; };", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInAsyncVoidAnonymousMethod(TestMode mode) { await TestInMethodAsync( @"System.Action f = async delegate () { return [|Goo()|]; };", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnAsGlobalStatement(TestMode mode) { await TestAsync( @"return [|Goo()|];", "global::System.Object", mode, sourceCodeKind: SourceCodeKind.Script); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestSimpleLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<string, int> f = s => [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestParenthesizedLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<int> f = () => [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(30232, "https://github.com/dotnet/roslyn/issues/30232")] public async Task TestAsyncTaskOfTSimpleLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<string, System.Threading.Tasks.Task<int>> f = async s => [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestAsyncTaskOfTSimpleLambdaWithNullableReturn(TestMode mode) { await TestInMethodAsync( @"#nullable enable System.Func<string, System.Threading.Tasks.Task<string?>> f = async s => [|Goo()|];", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(30232, "https://github.com/dotnet/roslyn/issues/30232")] public async Task TestAsyncTaskOfTParenthesizedLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<System.Threading.Tasks.Task<int>> f = async () => [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(30232, "https://github.com/dotnet/roslyn/issues/30232")] public async Task TestAsyncTaskSimpleLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<string, System.Threading.Tasks.Task> f = async s => [|Goo()|];", "void", mode); } [WorkItem(30232, "https://github.com/dotnet/roslyn/issues/30232")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestAsyncTaskParenthesizedLambda(TestMode mode) { await TestInMethodAsync( @"System.Func<System.Threading.Tasks.Task> f = async () => [|Goo()|];", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestAsyncVoidSimpleLambda(TestMode mode) { await TestInMethodAsync( @"System.Action<string> f = async s => [|Goo()|];", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestAsyncVoidParenthesizedLambda(TestMode mode) { await TestInMethodAsync( @"System.Action f = async () => [|Goo()|];", "void", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionTreeSimpleLambda(TestMode mode) { await TestInMethodAsync( @"System.Linq.Expressions.Expression<System.Func<string, int>> f = s => [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestExpressionTreeParenthesizedLambda(TestMode mode) { await TestInMethodAsync( @"System.Linq.Expressions.Expression<System.Func<int>> f = () => [|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestThrow(TestMode mode) { await TestInMethodAsync( @"throw [|Goo()|];", "global::System.Exception", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCatch(TestMode mode) => await TestInMethodAsync("try { } catch ([|Goo|] ex) { }", "global::System.Exception", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIf(TestMode mode) => await TestInMethodAsync(@"if ([|Goo()|]) { }", "global::System.Boolean", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestWhile(TestMode mode) => await TestInMethodAsync(@"while ([|Goo()|]) { }", "global::System.Boolean", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestDo(TestMode mode) => await TestInMethodAsync(@"do { } while ([|Goo()|])", "global::System.Boolean", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestFor1(TestMode mode) { await TestInMethodAsync( @"for (int i = 0; [|Goo()|]; i++) { }", "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestFor2(TestMode mode) => await TestInMethodAsync(@"for (string i = [|Goo()|]; ; ) { }", "global::System.String", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestFor3(TestMode mode) => await TestInMethodAsync(@"for (var i = [|Goo()|]; ; ) { }", "global::System.Int32", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestForNullableReference(TestMode mode) { await TestInMethodAsync( @"#nullable enable for (string? s = [|Goo()|]; ; ) { }", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestUsing1(TestMode mode) => await TestInMethodAsync(@"using ([|Goo()|]) { }", "global::System.IDisposable", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestUsing2(TestMode mode) => await TestInMethodAsync(@"using (int i = [|Goo()|]) { }", "global::System.Int32", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestUsing3(TestMode mode) => await TestInMethodAsync(@"using (var v = [|Goo()|]) { }", "global::System.IDisposable", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestForEach(TestMode mode) => await TestInMethodAsync(@"foreach (int v in [|Goo()|]) { }", "global::System.Collections.Generic.IEnumerable<global::System.Int32>", mode); [Theory(Skip = "https://github.com/dotnet/roslyn/issues/37309"), CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestForEachNullableElements(TestMode mode) { await TestInMethodAsync( @"#nullable enable foreach (string? v in [|Goo()|]) { }", "global::System.Collections.Generic.IEnumerable<global::System.String?>", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression1(TestMode mode) { await TestInMethodAsync( @"var q = +[|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression2(TestMode mode) { await TestInMethodAsync( @"var q = -[|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression3(TestMode mode) { await TestInMethodAsync( @"var q = ~[|Goo()|];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression4(TestMode mode) { await TestInMethodAsync( @"var q = ![|Goo()|];", "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression5(TestMode mode) { await TestInMethodAsync( @"var q = System.DayOfWeek.Monday & ~[|Goo()|];", "global::System.DayOfWeek", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayRankSpecifier(TestMode mode) { await TestInMethodAsync( @"var q = new string[[|Goo()|]];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestSwitch1(TestMode mode) => await TestInMethodAsync(@"switch ([|Goo()|]) { }", "global::System.Int32", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestSwitch2(TestMode mode) => await TestInMethodAsync(@"switch ([|Goo()|]) { default: }", "global::System.Int32", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestSwitch3(TestMode mode) => await TestInMethodAsync(@"switch ([|Goo()|]) { case ""a"": }", "global::System.String", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall1(TestMode mode) { await TestInMethodAsync( @"Bar([|Goo()|]);", "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall2(TestMode mode) { await TestInClassAsync( @"void M() { Bar([|Goo()|]); } void Bar(int i);", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall3(TestMode mode) { await TestInClassAsync( @"void M() { Bar([|Goo()|]); } void Bar();", "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall4(TestMode mode) { await TestInClassAsync( @"void M() { Bar([|Goo()|]); } void Bar(int i, string s);", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall5(TestMode mode) { await TestInClassAsync( @"void M() { Bar(s: [|Goo()|]); } void Bar(int i, string s);", "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCallNullableReference(TestMode mode) { await TestInClassAsync( @"void M() { Bar([|Goo()|]); } void Bar(string? s);", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall1(TestMode mode) { await TestInMethodAsync( @"new C([|Goo()|]);", "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall2(TestMode mode) { await TestInClassAsync( @"void M() { new C([|Goo()|]); } C(int i) { }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall3(TestMode mode) { await TestInClassAsync( @"void M() { new C([|Goo()|]); } C() { }", "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall4(TestMode mode) { await TestInClassAsync( @"void M() { new C([|Goo()|]); } C(int i, string s) { }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall5(TestMode mode) { await TestInClassAsync( @"void M() { new C(s: [|Goo()|]); } C(int i, string s) { }", "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCallNullableParameter(TestMode mode) { await TestInClassAsync( @"#nullable enable void M() { new C([|Goo()|]); } C(string? s) { }", "global::System.String?", mode); } [WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestThisConstructorInitializer1(TestMode mode) { await TestAsync( @"class MyClass { public MyClass(int x) : this([|test|]) { } }", "global::System.Int32", mode); } [WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestThisConstructorInitializer2(TestMode mode) { await TestAsync( @"class MyClass { public MyClass(int x, string y) : this(5, [|test|]) { } }", "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestThisConstructorInitializerNullableParameter(TestMode mode) { await TestAsync( @"#nullable enable class MyClass { public MyClass(string? y) : this([|test|]) { } }", "global::System.String?", mode); } [WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBaseConstructorInitializer(TestMode mode) { await TestAsync( @"class B { public B(int x) { } } class D : B { public D() : base([|test|]) { } }", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBaseConstructorInitializerNullableParameter(TestMode mode) { await TestAsync( @"#nullable enable class B { public B(string? x) { } } class D : B { public D() : base([|test|]) { } }", "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexAccess1(TestMode mode) { await TestInMethodAsync( @"string[] i; i[[|Goo()|]];", "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexerCall1(TestMode mode) => await TestInMethodAsync(@"this[[|Goo()|]];", "global::System.Int32", mode); [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexerCall2(TestMode mode) { await TestInClassAsync( @"void M() { this[[|Goo()|]]; } int this[long i] { get; }", "global::System.Int64", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexerCall3(TestMode mode) { await TestInClassAsync( @"void M() { this[42, [|Goo()|]]; } int this[int i, string s] { get; }", "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexerCall5(TestMode mode) { await TestInClassAsync( @"void M() { this[s: [|Goo()|]]; } int this[int i, string s] { get; }", "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInitializerInImplicitArrayCreationSimple(TestMode mode) { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { 1, [|2|] }; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInitializerInImplicitArrayCreation1(TestMode mode) { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Goo()|] }; } int Bar() { return 1; } int Goo() { return 2; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInitializerInImplicitArrayCreation2(TestMode mode) { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Goo()|] }; } int Bar() { return 1; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInitializerInImplicitArrayCreation3(TestMode mode) { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Goo()|] }; } }"; await TestAsync(text, "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInitializerInImplicitArrayCreationInferredAsNullable(TestMode mode) { var text = @"#nullable enable using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Goo()|] }; } object? Bar() { return null; } }"; await TestAsync(text, "global::System.Object?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInitializerInEqualsValueClauseSimple(TestMode mode) { var text = @"using System.Collections.Generic; class C { void M() { int[] a = { 1, [|2|] }; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInitializerInEqualsValueClause(TestMode mode) { var text = @"using System.Collections.Generic; class C { void M() { int[] a = { Bar(), [|Goo()|] }; } int Bar() { return 1; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInitializerInEqualsValueClauseNullableElement(TestMode mode) { var text = @"#nullable enable using System.Collections.Generic; class C { void M() { string?[] a = { [|Goo()|] }; } }"; await TestAsync(text, "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] public async Task TestCollectionInitializer1(TestMode mode) { var text = @"using System.Collections.Generic; class C { void M() { new List<int>() { [|Goo()|] }; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCollectionInitializerNullableElement(TestMode mode) { var text = @"#nullable enable using System.Collections.Generic; class C { void M() { new List<string?>() { [|Goo()|] }; } }"; await TestAsync(text, "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] public async Task TestCollectionInitializer2(TestMode mode) { var text = @" using System.Collections.Generic; class C { void M() { new Dictionary<int,string>() { { [|Goo()|], """" } }; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] public async Task TestCollectionInitializer3(TestMode mode) { var text = @" using System.Collections.Generic; class C { void M() { new Dictionary<int,string>() { { 0, [|Goo()|] } }; } }"; await TestAsync(text, "global::System.String", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] public async Task TestCustomCollectionInitializerAddMethod1() { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { [|a|] }; } void Add(int i) { } void Add(string s, bool b) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; await TestAsync(text, "global::System.Int32", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] public async Task TestCustomCollectionInitializerAddMethod2(TestMode mode) { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { { ""test"", [|b|] } }; } void Add(int i) { } void Add(string s, bool b) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; await TestAsync(text, "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] public async Task TestCustomCollectionInitializerAddMethod3(TestMode mode) { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { { [|s|], true } }; } void Add(int i) { } void Add(string s, bool b) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; await TestAsync(text, "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCustomCollectionInitializerAddMethodWithNullableParameter(TestMode mode) { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { { ""test"", [|s|] } }; } void Add(int i) { } void Add(string s, string? s2) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; await TestAsync(text, "global::System.String?", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference1() { var text = @" class A { void Goo() { A[] x = new [|C|][] { }; } }"; await TestAsync(text, "global::A", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference1_Position() { var text = @" class A { void Goo() { A[] x = new [|C|][] { }; } }"; await TestAsync(text, "global::A[]", TestMode.Position); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference2() { var text = @" class A { void Goo() { A[][] x = new [|C|][][] { }; } }"; await TestAsync(text, "global::A", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference2_Position() { var text = @" class A { void Goo() { A[][] x = new [|C|][][] { }; } }"; await TestAsync(text, "global::A[][]", TestMode.Position); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference3() { var text = @" class A { void Goo() { A[][] x = new [|C|][] { }; } }"; await TestAsync(text, "global::A[]", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference3_Position() { var text = @" class A { void Goo() { A[][] x = new [|C|][] { }; } }"; await TestAsync(text, "global::A[][]", TestMode.Position); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference4(TestMode mode) { var text = @" using System; class A { void Goo() { Func<int, int>[] x = new Func<int, int>[] { [|Bar()|] }; } }"; await TestAsync(text, "global::System.Func<global::System.Int32, global::System.Int32>", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(538993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538993")] public async Task TestInsideLambda2(TestMode mode) { var text = @"using System; class C { void M() { Func<int,int> f = i => [|here|] } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestInsideLambdaNullableReturn(TestMode mode) { var text = @"#nullable enable using System; class C { void M() { Func<int, string?> f = i => [|here|] } }"; await TestAsync(text, "global::System.String?", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(539813, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539813")] public async Task TestPointer1(TestMode mode) { var text = @"class C { void M(int* i) { var q = i[[|Goo()|]]; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(539813, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539813")] public async Task TestDynamic1(TestMode mode) { var text = @"class C { void M(dynamic i) { var q = i[[|Goo()|]]; } }"; await TestAsync(text, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestChecked1(TestMode mode) { var text = @"class C { void M() { string q = checked([|Goo()|]); } }"; await TestAsync(text, "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(553584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553584")] public async Task TestAwaitTaskOfT(TestMode mode) { var text = @"using System.Threading.Tasks; class C { void M() { int x = await [|Goo()|]; } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Int32>", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestAwaitTaskOfTNullableValue(TestMode mode) { var text = @"#nullable enable using System.Threading.Tasks; class C { void M() { string? x = await [|Goo()|]; } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.String?>", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(553584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553584")] public async Task TestAwaitTaskOfTaskOfT(TestMode mode) { var text = @"using System.Threading.Tasks; class C { void M() { Task<int> x = await [|Goo()|]; } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Threading.Tasks.Task<global::System.Int32>>", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(553584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553584")] public async Task TestAwaitTask(TestMode mode) { var text = @"using System.Threading.Tasks; class C { void M() { await [|Goo()|]; } }"; await TestAsync(text, "global::System.Threading.Tasks.Task", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617622")] public async Task TestLockStatement(TestMode mode) { var text = @"class C { void M() { lock([|Goo()|]) { } } }"; await TestAsync(text, "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617622")] public async Task TestAwaitExpressionInLockStatement(TestMode mode) { var text = @"class C { async void M() { lock(await [|Goo()|]) { } } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Object>", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(827897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827897")] public async Task TestReturnFromAsyncTaskOfT(TestMode mode) { var markup = @"using System.Threading.Tasks; class Program { async Task<int> M() { await Task.Delay(1); return [|ab|] } }"; await TestAsync(markup, "global::System.Int32", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(853840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853840")] public async Task TestAttributeArguments1(TestMode mode) { var markup = @"[A([|dd|], ee, Y = ff)] class AAttribute : System.Attribute { public int X; public string Y; public AAttribute(System.DayOfWeek a, double b) { } }"; await TestAsync(markup, "global::System.DayOfWeek", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(853840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853840")] public async Task TestAttributeArguments2(TestMode mode) { var markup = @"[A(dd, [|ee|], Y = ff)] class AAttribute : System.Attribute { public int X; public string Y; public AAttribute(System.DayOfWeek a, double b) { } }"; await TestAsync(markup, "global::System.Double", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(853840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853840")] public async Task TestAttributeArguments3(TestMode mode) { var markup = @"[A(dd, ee, Y = [|ff|])] class AAttribute : System.Attribute { public int X; public string Y; public AAttribute(System.DayOfWeek a, double b) { } }"; await TestAsync(markup, "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(757111, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/757111")] public async Task TestReturnStatementWithinDelegateWithinAMethodCall(TestMode mode) { var text = @"using System; class Program { delegate string A(int i); static void Main(string[] args) { B(delegate(int i) { return [|M()|]; }); } private static void B(A a) { } }"; await TestAsync(text, "global::System.String", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(994388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994388")] public async Task TestCatchFilterClause(TestMode mode) { var text = @" try { } catch (Exception) if ([|M()|]) }"; await TestInMethodAsync(text, "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(994388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994388")] public async Task TestCatchFilterClause1(TestMode mode) { var text = @" try { } catch (Exception) if ([|M|]) }"; await TestInMethodAsync(text, "global::System.Boolean", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(994388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994388")] public async Task TestCatchFilterClause2() { var text = @" try { } catch (Exception) if ([|M|].N) }"; await TestInMethodAsync(text, "global::System.Object", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")] public async Task TestAwaitExpressionWithChainingMethod() { var text = @"using System; using System.Threading.Tasks; class C { static async void T() { bool x = await [|M()|].ConfigureAwait(false); } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Boolean>", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")] public async Task TestAwaitExpressionWithChainingMethod2() { var text = @"using System; using System.Threading.Tasks; class C { static async void T() { bool x = await [|M|].ContinueWith(a => { return true; }).ContinueWith(a => { return false; }); } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Object>", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4233, "https://github.com/dotnet/roslyn/issues/4233")] public async Task TestAwaitExpressionWithGenericMethod1() { var text = @"using System.Threading.Tasks; public class C { private async void M() { bool merged = await X([|Test()|]); } private async Task<T> X<T>(T t) { return t; } }"; await TestAsync(text, "global::System.Boolean", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4233, "https://github.com/dotnet/roslyn/issues/4233")] public async Task TestAwaitExpressionWithGenericMethod2(TestMode mode) { var text = @"using System.Threading.Tasks; public class C { private async void M() { bool merged = await Task.Run(() => [|Test()|]);; } private async Task<T> X<T>(T t) { return t; } }"; await TestAsync(text, "global::System.Boolean", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")] public async Task TestNullCoalescingOperator1(TestMode mode) { var text = @"class C { void M() { object z = [|a|] ?? null; } }"; // In position mode, we are inferring that the thing to the right is an object, because it's being assigned to a local of type object. // In node mode, we are inferring the node is an object? because it's to the left of the ??. await TestAsync(text, mode == TestMode.Node ? "global::System.Object?" : "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")] public async Task TestNullCoalescingOperator2(TestMode mode) { var text = @"class C { void M() { object z = [|a|] ?? b ?? c; } }"; // In position mode, we are inferring that the thing to the right is an object, because it's being assigned to a local of type object. // In node mode, we are inferring the node is an object? because it's to the left of the ??. await TestAsync(text, mode == TestMode.Node ? "global::System.Object?" : "global::System.Object", mode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")] public async Task TestNullCoalescingOperator3(TestMode mode) { var text = @"class C { void M() { object z = a ?? [|b|] ?? c; } }"; // In position mode, we are inferring that the thing to the right is an object, because it's to the right of the first ?? // and thus must be the same type as the object being assigned to. // In node mode, we are inferring the node is an object? because it's to the left of the ??. await TestAsync(text, mode == TestMode.Node ? "global::System.Object?" : "global::System.Object", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(5126, "https://github.com/dotnet/roslyn/issues/5126")] public async Task TestSelectLambda() { var text = @"using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<string> args) { args = args.Select(a =>[||]) } }"; await TestAsync(text, "global::System.Object", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(5126, "https://github.com/dotnet/roslyn/issues/5126")] public async Task TestSelectLambda2() { var text = @"using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<string> args) { args = args.Select(a =>[|b|]) } }"; await TestAsync(text, "global::System.String", TestMode.Node); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(1903, "https://github.com/dotnet/roslyn/issues/1903")] public async Task TestSelectLambda3(TestMode mode) { var text = @"using System.Collections.Generic; using System.Linq; class A { } class B { } class C { IEnumerable<B> GetB(IEnumerable<A> a) { return a.Select(i => [|Goo(i)|]); } }"; await TestAsync(text, "global::B", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(6765, "https://github.com/dotnet/roslyn/issues/6765")] public async Task TestDefaultStatement1() { var text = @"class C { static void Main(string[] args) { System.ConsoleModifiers c = default([||]) } }"; await TestAsync(text, "global::System.ConsoleModifiers", TestMode.Position); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(6765, "https://github.com/dotnet/roslyn/issues/6765")] public async Task TestDefaultStatement2() { var text = @"class C { static void Goo(System.ConsoleModifiers arg) { Goo(default([||]) } }"; await TestAsync(text, "global::System.ConsoleModifiers", TestMode.Position); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestWhereCall() { var text = @" using System.Collections.Generic; class C { void Goo() { [|ints|].Where(i => i > 10); } }"; await TestAsync(text, "global::System.Collections.Generic.IEnumerable<global::System.Int32>", TestMode.Node); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestWhereCall2() { var text = @" using System.Collections.Generic; class C { void Goo() { [|ints|].Where(i => null); } }"; await TestAsync(text, "global::System.Collections.Generic.IEnumerable<global::System.Object>", TestMode.Node); } [WorkItem(12755, "https://github.com/dotnet/roslyn/issues/12755")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestObjectCreationBeforeArrayIndexing() { var text = @"using System; class C { void M() { int[] array; C p = new [||] array[4] = 4; } }"; await TestAsync(text, "global::C", TestMode.Position); } [WorkItem(15468, "https://github.com/dotnet/roslyn/issues/15468")] [WorkItem(25305, "https://github.com/dotnet/roslyn/issues/25305")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestDeconstruction() { await TestInMethodAsync( @"[|(int i, _)|] =", "(global::System.Int32 i, global::System.Object _)", TestMode.Node); } [WorkItem(15468, "https://github.com/dotnet/roslyn/issues/15468")] [WorkItem(25305, "https://github.com/dotnet/roslyn/issues/25305")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestDeconstruction2() { await TestInMethodAsync( @"(int i, _) = [||]", "(global::System.Int32 i, global::System.Object _)", TestMode.Position); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestDeconstructionWithNullableElement() { await TestInMethodAsync( @"[|(string? s, _)|] =", "(global::System.String? s, global::System.Object _)", TestMode.Node); } [WorkItem(13402, "https://github.com/dotnet/roslyn/issues/13402")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestObjectCreationBeforeBlock() { var text = @"class Program { static void Main(string[] args) { Program p = new [||] { } } }"; await TestAsync(text, "global::Program", TestMode.Position); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestInferringThroughGenericFunctionWithNullableReturn(TestMode mode) { var text = @"#nullable enable class Program { static void Main(string[] args) { string? s = Identity([|input|]); } static T Identity<T>(T value) { return value; } }"; await TestAsync(text, "global::System.String?", mode); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestInferringThroughGenericFunctionMissingArgument() { var text = @"class Program { static void Main(string[] args) { string s = Identity([||]); } static T Identity<T>(T value) { return value; } }"; await TestAsync(text, "global::System.String", TestMode.Position); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestInferringThroughGenericFunctionTooManyArguments(TestMode mode) { var text = @"class Program { static void Main(string[] args) { string s = Identity(""test"", [||]); } static T Identity<T>(T value) { return value; } }"; await TestAsync(text, "global::System.Object", mode); } [WorkItem(14277, "https://github.com/dotnet/roslyn/issues/14277")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestValueInNestedTuple1(TestMode mode) { await TestInMethodAsync( @"(int, (string, bool)) x = ([|Goo()|], ("""", true));", "global::System.Int32", mode); } [WorkItem(14277, "https://github.com/dotnet/roslyn/issues/14277")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestValueInNestedTuple2(TestMode mode) { await TestInMethodAsync( @"(int, (string, bool)) x = (1, ("""", [|Goo()|]));", "global::System.Boolean", mode); } [WorkItem(14277, "https://github.com/dotnet/roslyn/issues/14277")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestValueInNestedTuple3() { await TestInMethodAsync( @"(int, string) x = (1, [||]);", "global::System.String", TestMode.Position); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestInferringInEnumHasFlags(TestMode mode) { var text = @"using System.IO; class Program { static void Main(string[] args) { FileInfo f; f.Attributes.HasFlag([|flag|]); } }"; await TestAsync(text, "global::System.IO.FileAttributes", mode); } [Theory] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [InlineData("")] [InlineData("Re")] [InlineData("Col")] [InlineData("Color.Green or", false)] [InlineData("Color.Green or ")] [InlineData("(Color.Green or ")] // start of: is (Color.Red or Color.Green) and not Color.Blue [InlineData("Color.Green or Re")] [InlineData("Color.Green or Color.Red or ")] [InlineData("Color.Green orWrittenWrong ", false)] [InlineData("not ")] [InlineData("not Re")] public async Task TestEnumInPatterns_Is_ConstUnaryAndBinaryPattern(string isPattern, bool shouldInferColor = true) { var markup = @$" class C {{ public enum Color {{ Red, Green, }} public void M(Color c) {{ var isRed = c is {isPattern}[||]; }} }} "; var expectedType = shouldInferColor ? "global::C.Color" : "global::System.Object"; await TestAsync(markup, expectedType, TestMode.Position); } [Theory] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [InlineData("")] [InlineData("Col")] [InlineData("Color.R")] [InlineData("Red")] [InlineData("Color.Green or ")] [InlineData("Color.Green or Re")] [InlineData("not ")] [InlineData("not Re")] public async Task TestEnumInPatterns_Is_PropertyPattern(string partialWritten) { var markup = @$" public enum Color {{ Red, Green, }} class C {{ public Color Color {{ get; }} public void M() {{ var isRed = this is {{ Color: {partialWritten}[||] }} }} "; await TestAsync(markup, "global::Color", TestMode.Position); } [Fact] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestEnumInPatterns_SwitchStatement_PropertyPattern() { var markup = @" public enum Color { Red, Green, } class C { public Color Color { get; } public void M() { switch (this) { case { Color: [||] } } "; await TestAsync(markup, "global::Color", TestMode.Position); } [Fact] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestEnumInPatterns_SwitchExpression_PropertyPattern() { var markup = @" public enum Color { Red, Green, } class C { public Color Color { get; } public void M() { var isRed = this switch { { Color: [||] } } "; await TestAsync(markup, "global::Color", TestMode.Position); } [Fact] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestEnumInPatterns_SwitchStatement_ExtendedPropertyPattern() { var markup = @" public enum Color { Red, Green, } class C { public C AnotherC { get; } public Color Color { get; } public void M() { switch (this) { case { AnotherC.Color: [||] } } "; await TestAsync(markup, "global::Color", TestMode.Position); } [Fact] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestEnumInPatterns_SwitchStatement_ExtendedPropertyPattern_Field() { var markup = @" public enum Color { Red, Green, } class C { public C AnotherC { get; } public Color Color; public void M() { switch (this) { case { AnotherC.Color: [||] } } "; await TestAsync(markup, "global::Color", TestMode.Position); } } }
-1
dotnet/roslyn
55,066
Correctly set IsRetargetable for source assemblies
Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
333fred
2021-07-23T00:55:50Z
2021-07-24T00:08:23Z
a3b5d0f87fbdceadf6d3d1b024aca4736e3e079e
c58fbd573ea1ca0273ef3878782baab73d5201c8
Correctly set IsRetargetable for source assemblies. Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
./src/Scripting/Core/xlf/ScriptingResources.it.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="it" original="../ScriptingResources.resx"> <body> <trans-unit id="CannotSetLanguageSpecificOption"> <source>Cannot set {0} specific option {1} because the options were already configured for a different language.</source> <target state="translated">Non è possibile impostare l'opzione {1} specifica di {0} perché le opzioni sono già state configurate per un linguaggio diverso.</target> <note /> </trans-unit> <trans-unit id="StackOverflowWhileEvaluating"> <source>!&lt;Stack overflow while evaluating object&gt;</source> <target state="translated">!&lt;Overflow dello stack durante la valutazione dell'oggetto&gt;</target> <note /> </trans-unit> <trans-unit id="CantAssignTo"> <source>Can't assign '{0}' to '{1}'.</source> <target state="translated">Non è possibile assegnare '{0}' a '{1}'.</target> <note /> </trans-unit> <trans-unit id="ExpectedAnAssemblyReference"> <source>Expected an assembly reference.</source> <target state="translated">È previsto un riferimento ad assembly.</target> <note /> </trans-unit> <trans-unit id="DisplayNameOrPathCannotBe"> <source>Display name or path cannot be empty.</source> <target state="translated">Il nome visualizzato o il percorso non può essere vuoto.</target> <note /> </trans-unit> <trans-unit id="AbsolutePathExpected"> <source>Absolute path expected</source> <target state="translated">È previsto il percorso assoluto</target> <note /> </trans-unit> <trans-unit id="GlobalsNotAssignable"> <source>The globals of type '{0}' is not assignable to '{1}'</source> <target state="translated">Le variabili globali di tipo '{0}' non sono assegnabili a '{1}'</target> <note /> </trans-unit> <trans-unit id="StartingStateIncompatible"> <source>Starting state was incompatible with script.</source> <target state="translated">Lo stato iniziale non è compatibile con lo script.</target> <note /> </trans-unit> <trans-unit id="InvalidAssemblyName"> <source>Invalid assembly name</source> <target state="translated">Nome di assembly non valido</target> <note /> </trans-unit> <trans-unit id="InvalidCharactersInAssemblyName"> <source>Invalid characters in assemblyName</source> <target state="translated">Caratteri non validi nel nome dell'assembly</target> <note /> </trans-unit> <trans-unit id="ScriptRequiresGlobalVariables"> <source>The script requires access to global variables but none were given</source> <target state="translated">Lo script richiede l'accesso a variabili globali, ma non ne è stata specificata nessuna</target> <note /> </trans-unit> <trans-unit id="GlobalVariablesWithoutGlobalType"> <source>Global variables passed to a script without a global type</source> <target state="translated">A uno script sono state passate variabili globali senza un tipo globale</target> <note /> </trans-unit> <trans-unit id="PlusAdditionalError"> <source>+ additional {0} error</source> <target state="translated">+ {0} altro errore</target> <note /> </trans-unit> <trans-unit id="PlusAdditionalErrors"> <source>+ additional {0} errors</source> <target state="translated">+ altri {0} errori</target> <note /> </trans-unit> <trans-unit id="AtFileLine"> <source> at {0} : {1}</source> <target state="translated"> a {0}: {1}</target> <note /> </trans-unit> <trans-unit id="CannotSetReadOnlyVariable"> <source>Cannot set a read-only variable</source> <target state="translated">Non è possibile impostare una variabile di sola lettura</target> <note /> </trans-unit> <trans-unit id="CannotSetConstantVariable"> <source>Cannot set a constant variable</source> <target state="translated">Non è possibile impostare una variabile costante</target> <note /> </trans-unit> <trans-unit id="HelpPrompt"> <source>Type "#help" for more information.</source> <target state="translated">Per altre informazioni, digitare "#help".</target> <note /> </trans-unit> <trans-unit id="HelpText"> <source>Keyboard shortcuts: Enter If the current submission appears to be complete, evaluate it. Otherwise, insert a new line. Escape Clear the current submission. UpArrow Replace the current submission with a previous submission. DownArrow Replace the current submission with a subsequent submission (after having previously navigated backwards). Ctrl-C Exit the REPL. REPL commands: #help Display help on available commands and key bindings. Script directives: #r Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll". #load Load specified script file and execute it, e.g. #load "myScript.csx".</source> <target state="translated">Tasti di scelta rapida: INVIO Valuta se l'invio corrente sembra completo; in caso contrario, inserisce una nuova riga. ESC Cancella l'invio corrente. Freccia SU Sostituisce l'invio corrente con uno precedente. Freccia GIÙ Sostituisce l'invio corrente con uno successivo dopo che è stato eseguito uno spostamento all'indietro. CTRL+C Esce da REPL. Comandi REPL: #help Visualizza la guida relativa ai comandi e i tasti di scelta rapida disponibili. Direttive script: #r Aggiunge un riferimento ai metadati all'assembly specificato e a tutte le relative dipendenze, ad esempio #r "LibPersonale.dll". #load Carica il file di script specificato e lo esegue, ad esempio #load "ScriptPersonale.csx".</target> <note /> </trans-unit> <trans-unit id="AssemblyAlreadyLoaded"> <source>Assembly '{0}, Version={1}' has already been loaded from '{2}'. A different assembly with the same name and version can't be loaded: '{3}'.</source> <target state="translated">L'assembly '{0}, Version={1}' è già stato caricato da '{2}'. Non è possibile caricare un assembly con lo stesso nome e la stessa versione: '{3}'.</target> <note /> </trans-unit> <trans-unit id="AssemblyAlreadyLoadedNotSigned"> <source>Assembly '{0}' has already been loaded from '{1}'. A different assembly with the same name can't be loaded unless it's signed: '{2}'.</source> <target state="translated">L'assembly '{0}' è già stato caricato da '{1}'. Non è possibile caricare un assembly diverso con lo stesso nome a meno che non sia firmato: '{2}'.</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="it" original="../ScriptingResources.resx"> <body> <trans-unit id="CannotSetLanguageSpecificOption"> <source>Cannot set {0} specific option {1} because the options were already configured for a different language.</source> <target state="translated">Non è possibile impostare l'opzione {1} specifica di {0} perché le opzioni sono già state configurate per un linguaggio diverso.</target> <note /> </trans-unit> <trans-unit id="StackOverflowWhileEvaluating"> <source>!&lt;Stack overflow while evaluating object&gt;</source> <target state="translated">!&lt;Overflow dello stack durante la valutazione dell'oggetto&gt;</target> <note /> </trans-unit> <trans-unit id="CantAssignTo"> <source>Can't assign '{0}' to '{1}'.</source> <target state="translated">Non è possibile assegnare '{0}' a '{1}'.</target> <note /> </trans-unit> <trans-unit id="ExpectedAnAssemblyReference"> <source>Expected an assembly reference.</source> <target state="translated">È previsto un riferimento ad assembly.</target> <note /> </trans-unit> <trans-unit id="DisplayNameOrPathCannotBe"> <source>Display name or path cannot be empty.</source> <target state="translated">Il nome visualizzato o il percorso non può essere vuoto.</target> <note /> </trans-unit> <trans-unit id="AbsolutePathExpected"> <source>Absolute path expected</source> <target state="translated">È previsto il percorso assoluto</target> <note /> </trans-unit> <trans-unit id="GlobalsNotAssignable"> <source>The globals of type '{0}' is not assignable to '{1}'</source> <target state="translated">Le variabili globali di tipo '{0}' non sono assegnabili a '{1}'</target> <note /> </trans-unit> <trans-unit id="StartingStateIncompatible"> <source>Starting state was incompatible with script.</source> <target state="translated">Lo stato iniziale non è compatibile con lo script.</target> <note /> </trans-unit> <trans-unit id="InvalidAssemblyName"> <source>Invalid assembly name</source> <target state="translated">Nome di assembly non valido</target> <note /> </trans-unit> <trans-unit id="InvalidCharactersInAssemblyName"> <source>Invalid characters in assemblyName</source> <target state="translated">Caratteri non validi nel nome dell'assembly</target> <note /> </trans-unit> <trans-unit id="ScriptRequiresGlobalVariables"> <source>The script requires access to global variables but none were given</source> <target state="translated">Lo script richiede l'accesso a variabili globali, ma non ne è stata specificata nessuna</target> <note /> </trans-unit> <trans-unit id="GlobalVariablesWithoutGlobalType"> <source>Global variables passed to a script without a global type</source> <target state="translated">A uno script sono state passate variabili globali senza un tipo globale</target> <note /> </trans-unit> <trans-unit id="PlusAdditionalError"> <source>+ additional {0} error</source> <target state="translated">+ {0} altro errore</target> <note /> </trans-unit> <trans-unit id="PlusAdditionalErrors"> <source>+ additional {0} errors</source> <target state="translated">+ altri {0} errori</target> <note /> </trans-unit> <trans-unit id="AtFileLine"> <source> at {0} : {1}</source> <target state="translated"> a {0}: {1}</target> <note /> </trans-unit> <trans-unit id="CannotSetReadOnlyVariable"> <source>Cannot set a read-only variable</source> <target state="translated">Non è possibile impostare una variabile di sola lettura</target> <note /> </trans-unit> <trans-unit id="CannotSetConstantVariable"> <source>Cannot set a constant variable</source> <target state="translated">Non è possibile impostare una variabile costante</target> <note /> </trans-unit> <trans-unit id="HelpPrompt"> <source>Type "#help" for more information.</source> <target state="translated">Per altre informazioni, digitare "#help".</target> <note /> </trans-unit> <trans-unit id="HelpText"> <source>Keyboard shortcuts: Enter If the current submission appears to be complete, evaluate it. Otherwise, insert a new line. Escape Clear the current submission. UpArrow Replace the current submission with a previous submission. DownArrow Replace the current submission with a subsequent submission (after having previously navigated backwards). Ctrl-C Exit the REPL. REPL commands: #help Display help on available commands and key bindings. Script directives: #r Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll". #load Load specified script file and execute it, e.g. #load "myScript.csx".</source> <target state="translated">Tasti di scelta rapida: INVIO Valuta se l'invio corrente sembra completo; in caso contrario, inserisce una nuova riga. ESC Cancella l'invio corrente. Freccia SU Sostituisce l'invio corrente con uno precedente. Freccia GIÙ Sostituisce l'invio corrente con uno successivo dopo che è stato eseguito uno spostamento all'indietro. CTRL+C Esce da REPL. Comandi REPL: #help Visualizza la guida relativa ai comandi e i tasti di scelta rapida disponibili. Direttive script: #r Aggiunge un riferimento ai metadati all'assembly specificato e a tutte le relative dipendenze, ad esempio #r "LibPersonale.dll". #load Carica il file di script specificato e lo esegue, ad esempio #load "ScriptPersonale.csx".</target> <note /> </trans-unit> <trans-unit id="AssemblyAlreadyLoaded"> <source>Assembly '{0}, Version={1}' has already been loaded from '{2}'. A different assembly with the same name and version can't be loaded: '{3}'.</source> <target state="translated">L'assembly '{0}, Version={1}' è già stato caricato da '{2}'. Non è possibile caricare un assembly con lo stesso nome e la stessa versione: '{3}'.</target> <note /> </trans-unit> <trans-unit id="AssemblyAlreadyLoadedNotSigned"> <source>Assembly '{0}' has already been loaded from '{1}'. A different assembly with the same name can't be loaded unless it's signed: '{2}'.</source> <target state="translated">L'assembly '{0}' è già stato caricato da '{1}'. Non è possibile caricare un assembly diverso con lo stesso nome a meno che non sia firmato: '{2}'.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,066
Correctly set IsRetargetable for source assemblies
Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
333fred
2021-07-23T00:55:50Z
2021-07-24T00:08:23Z
a3b5d0f87fbdceadf6d3d1b024aca4736e3e079e
c58fbd573ea1ca0273ef3878782baab73d5201c8
Correctly set IsRetargetable for source assemblies. Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
./src/Compilers/CSharp/Portable/BoundTree/BoundTreeRewriter.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp { internal abstract partial class BoundTreeRewriter : BoundTreeVisitor { [return: NotNullIfNotNull("type")] public virtual TypeSymbol? VisitType(TypeSymbol? type) { return type; } public ImmutableArray<T> VisitList<T>(ImmutableArray<T> list) where T : BoundNode { if (list.IsDefault) { return list; } return DoVisitList(list); } private ImmutableArray<T> DoVisitList<T>(ImmutableArray<T> list) where T : BoundNode { ArrayBuilder<T>? newList = null; for (int i = 0; i < list.Length; i++) { var item = list[i]; System.Diagnostics.Debug.Assert(item != null); var visited = this.Visit(item); if (newList == null && item != visited) { newList = ArrayBuilder<T>.GetInstance(); if (i > 0) { newList.AddRange(list, i); } } if (newList != null && visited != null) { newList.Add((T)visited); } } if (newList != null) { return newList.ToImmutableAndFree(); } return list; } } internal abstract class BoundTreeRewriterWithStackGuard : BoundTreeRewriter { private int _recursionDepth; protected BoundTreeRewriterWithStackGuard() { } protected BoundTreeRewriterWithStackGuard(int recursionDepth) { _recursionDepth = recursionDepth; } protected int RecursionDepth => _recursionDepth; public override BoundNode? Visit(BoundNode? node) { var expression = node as BoundExpression; if (expression != null) { return VisitExpressionWithStackGuard(ref _recursionDepth, expression); } return base.Visit(node); } protected BoundExpression VisitExpressionWithStackGuard(BoundExpression node) { return VisitExpressionWithStackGuard(ref _recursionDepth, node); } protected sealed override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node) { return (BoundExpression)base.Visit(node); } } internal abstract class BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator : BoundTreeRewriterWithStackGuard { protected BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator() { } protected BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator(int recursionDepth) : base(recursionDepth) { } public sealed override BoundNode? VisitBinaryOperator(BoundBinaryOperator node) { BoundExpression child = node.Left; if (child.Kind != BoundKind.BinaryOperator) { return base.VisitBinaryOperator(node); } var stack = ArrayBuilder<BoundBinaryOperator>.GetInstance(); stack.Push(node); BoundBinaryOperator binary = (BoundBinaryOperator)child; while (true) { stack.Push(binary); child = binary.Left; if (child.Kind != BoundKind.BinaryOperator) { break; } binary = (BoundBinaryOperator)child; } var left = (BoundExpression?)this.Visit(child); Debug.Assert(left is { }); do { binary = stack.Pop(); var right = (BoundExpression?)this.Visit(binary.Right); Debug.Assert(right is { }); var type = this.VisitType(binary.Type); left = binary.Update(binary.OperatorKind, binary.Data, binary.ResultKind, left, right, type); } while (stack.Count > 0); Debug.Assert((object)binary == node); stack.Free(); return left; } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp { internal abstract partial class BoundTreeRewriter : BoundTreeVisitor { [return: NotNullIfNotNull("type")] public virtual TypeSymbol? VisitType(TypeSymbol? type) { return type; } public ImmutableArray<T> VisitList<T>(ImmutableArray<T> list) where T : BoundNode { if (list.IsDefault) { return list; } return DoVisitList(list); } private ImmutableArray<T> DoVisitList<T>(ImmutableArray<T> list) where T : BoundNode { ArrayBuilder<T>? newList = null; for (int i = 0; i < list.Length; i++) { var item = list[i]; System.Diagnostics.Debug.Assert(item != null); var visited = this.Visit(item); if (newList == null && item != visited) { newList = ArrayBuilder<T>.GetInstance(); if (i > 0) { newList.AddRange(list, i); } } if (newList != null && visited != null) { newList.Add((T)visited); } } if (newList != null) { return newList.ToImmutableAndFree(); } return list; } } internal abstract class BoundTreeRewriterWithStackGuard : BoundTreeRewriter { private int _recursionDepth; protected BoundTreeRewriterWithStackGuard() { } protected BoundTreeRewriterWithStackGuard(int recursionDepth) { _recursionDepth = recursionDepth; } protected int RecursionDepth => _recursionDepth; public override BoundNode? Visit(BoundNode? node) { var expression = node as BoundExpression; if (expression != null) { return VisitExpressionWithStackGuard(ref _recursionDepth, expression); } return base.Visit(node); } protected BoundExpression VisitExpressionWithStackGuard(BoundExpression node) { return VisitExpressionWithStackGuard(ref _recursionDepth, node); } protected sealed override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node) { return (BoundExpression)base.Visit(node); } } internal abstract class BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator : BoundTreeRewriterWithStackGuard { protected BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator() { } protected BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator(int recursionDepth) : base(recursionDepth) { } public sealed override BoundNode? VisitBinaryOperator(BoundBinaryOperator node) { BoundExpression child = node.Left; if (child.Kind != BoundKind.BinaryOperator) { return base.VisitBinaryOperator(node); } var stack = ArrayBuilder<BoundBinaryOperator>.GetInstance(); stack.Push(node); BoundBinaryOperator binary = (BoundBinaryOperator)child; while (true) { stack.Push(binary); child = binary.Left; if (child.Kind != BoundKind.BinaryOperator) { break; } binary = (BoundBinaryOperator)child; } var left = (BoundExpression?)this.Visit(child); Debug.Assert(left is { }); do { binary = stack.Pop(); var right = (BoundExpression?)this.Visit(binary.Right); Debug.Assert(right is { }); var type = this.VisitType(binary.Type); left = binary.Update(binary.OperatorKind, binary.Data, binary.ResultKind, left, right, type); } while (stack.Count > 0); Debug.Assert((object)binary == node); stack.Free(); return left; } } }
-1
dotnet/roslyn
55,066
Correctly set IsRetargetable for source assemblies
Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
333fred
2021-07-23T00:55:50Z
2021-07-24T00:08:23Z
a3b5d0f87fbdceadf6d3d1b024aca4736e3e079e
c58fbd573ea1ca0273ef3878782baab73d5201c8
Correctly set IsRetargetable for source assemblies. Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
./src/Features/Core/Portable/DocumentationComments/IDocumentationCommentSnippetService.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.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.DocumentationComments { internal interface IDocumentationCommentSnippetService : ILanguageService { /// <summary> /// A single character string indicating what the comment character is for the documentation comments /// </summary> string DocumentationCommentCharacter { get; } DocumentationCommentSnippet? GetDocumentationCommentSnippetOnCharacterTyped( SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken); DocumentationCommentSnippet? GetDocumentationCommentSnippetOnCommandInvoke( SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken); DocumentationCommentSnippet? GetDocumentationCommentSnippetOnEnterTyped( SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken); DocumentationCommentSnippet? GetDocumentationCommentSnippetFromPreviousLine( DocumentOptionSet options, TextLine currentLine, TextLine previousLine); bool IsValidTargetMember(SyntaxTree syntaxTree, SourceText text, int caretPosition, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.DocumentationComments { internal interface IDocumentationCommentSnippetService : ILanguageService { /// <summary> /// A single character string indicating what the comment character is for the documentation comments /// </summary> string DocumentationCommentCharacter { get; } DocumentationCommentSnippet? GetDocumentationCommentSnippetOnCharacterTyped( SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken); DocumentationCommentSnippet? GetDocumentationCommentSnippetOnCommandInvoke( SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken); DocumentationCommentSnippet? GetDocumentationCommentSnippetOnEnterTyped( SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken); DocumentationCommentSnippet? GetDocumentationCommentSnippetFromPreviousLine( DocumentOptionSet options, TextLine currentLine, TextLine previousLine); bool IsValidTargetMember(SyntaxTree syntaxTree, SourceText text, int caretPosition, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,066
Correctly set IsRetargetable for source assemblies
Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
333fred
2021-07-23T00:55:50Z
2021-07-24T00:08:23Z
a3b5d0f87fbdceadf6d3d1b024aca4736e3e079e
c58fbd573ea1ca0273ef3878782baab73d5201c8
Correctly set IsRetargetable for source assemblies. Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
./src/Compilers/VisualBasic/Portable/Symbols/SymbolVisitor`2.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.Generic Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Virtual dispatch based on a symbol's particular class. ''' </summary> ''' <typeparam name="TResult">Result type</typeparam> ''' <typeparam name="TArgument">Additional argument type</typeparam> Friend MustInherit Class VisualBasicSymbolVisitor(Of TArgument, TResult) ''' <summary> ''' Call the correct VisitXXX method in this class based on the particular type of symbol that is passed in. ''' </summary> Public Overridable Function Visit(symbol As Symbol, Optional arg As TArgument = Nothing) As TResult If symbol Is Nothing Then Return Nothing End If Return symbol.Accept(Me, arg) End Function Public Overridable Function DefaultVisit(symbol As Symbol, arg As TArgument) As TResult Return Nothing End Function Public Overridable Function VisitAlias(symbol As AliasSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitAssembly(symbol As AssemblySymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitModule(symbol As ModuleSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitNamespace(symbol As NamespaceSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitNamedType(symbol As NamedTypeSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitTypeParameter(symbol As TypeParameterSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitArrayType(symbol As ArrayTypeSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitErrorType(symbol As ErrorTypeSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitMethod(symbol As MethodSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitProperty(symbol As PropertySymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitField(symbol As FieldSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitParameter(symbol As ParameterSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitLocal(symbol As LocalSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitRangeVariable(symbol As RangeVariableSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitLabel(symbol As LabelSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitEvent(symbol As EventSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) 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.Generic Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Virtual dispatch based on a symbol's particular class. ''' </summary> ''' <typeparam name="TResult">Result type</typeparam> ''' <typeparam name="TArgument">Additional argument type</typeparam> Friend MustInherit Class VisualBasicSymbolVisitor(Of TArgument, TResult) ''' <summary> ''' Call the correct VisitXXX method in this class based on the particular type of symbol that is passed in. ''' </summary> Public Overridable Function Visit(symbol As Symbol, Optional arg As TArgument = Nothing) As TResult If symbol Is Nothing Then Return Nothing End If Return symbol.Accept(Me, arg) End Function Public Overridable Function DefaultVisit(symbol As Symbol, arg As TArgument) As TResult Return Nothing End Function Public Overridable Function VisitAlias(symbol As AliasSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitAssembly(symbol As AssemblySymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitModule(symbol As ModuleSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitNamespace(symbol As NamespaceSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitNamedType(symbol As NamedTypeSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitTypeParameter(symbol As TypeParameterSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitArrayType(symbol As ArrayTypeSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitErrorType(symbol As ErrorTypeSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitMethod(symbol As MethodSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitProperty(symbol As PropertySymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitField(symbol As FieldSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitParameter(symbol As ParameterSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitLocal(symbol As LocalSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitRangeVariable(symbol As RangeVariableSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitLabel(symbol As LabelSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitEvent(symbol As EventSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function End Class End Namespace
-1
dotnet/roslyn
55,066
Correctly set IsRetargetable for source assemblies
Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
333fred
2021-07-23T00:55:50Z
2021-07-24T00:08:23Z
a3b5d0f87fbdceadf6d3d1b024aca4736e3e079e
c58fbd573ea1ca0273ef3878782baab73d5201c8
Correctly set IsRetargetable for source assemblies. Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
./src/Features/VisualBasic/Portable/InvertConditional/VisualBasicInvertConditionalCodeRefactoringProvider.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.InvertConditional Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.InvertConditional <ExtensionOrder(Before:=PredefinedCodeRefactoringProviderNames.IntroduceVariable)> <ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.InvertConditional), [Shared]> Friend Class VisualBasicInvertConditionalCodeRefactoringProvider Inherits AbstractInvertConditionalCodeRefactoringProvider(Of TernaryConditionalExpressionSyntax) <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 ShouldOffer( conditional As TernaryConditionalExpressionSyntax) As Boolean Return Not conditional.FirstCommaToken.IsMissing AndAlso Not conditional.SecondCommaToken.IsMissing AndAlso Not conditional.CloseParenToken.IsMissing 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.InvertConditional Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.InvertConditional <ExtensionOrder(Before:=PredefinedCodeRefactoringProviderNames.IntroduceVariable)> <ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.InvertConditional), [Shared]> Friend Class VisualBasicInvertConditionalCodeRefactoringProvider Inherits AbstractInvertConditionalCodeRefactoringProvider(Of TernaryConditionalExpressionSyntax) <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 ShouldOffer( conditional As TernaryConditionalExpressionSyntax) As Boolean Return Not conditional.FirstCommaToken.IsMissing AndAlso Not conditional.SecondCommaToken.IsMissing AndAlso Not conditional.CloseParenToken.IsMissing End Function End Class End Namespace
-1
dotnet/roslyn
55,066
Correctly set IsRetargetable for source assemblies
Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
333fred
2021-07-23T00:55:50Z
2021-07-24T00:08:23Z
a3b5d0f87fbdceadf6d3d1b024aca4736e3e079e
c58fbd573ea1ca0273ef3878782baab73d5201c8
Correctly set IsRetargetable for source assemblies. Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationSymbol.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.Globalization; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CodeGeneration { internal abstract class CodeGenerationSymbol : ISymbol { protected static ConditionalWeakTable<CodeGenerationSymbol, SyntaxAnnotation[]> annotationsTable = new(); private ImmutableArray<AttributeData> _attributes; protected readonly string _documentationCommentXml; public Accessibility DeclaredAccessibility { get; } protected internal DeclarationModifiers Modifiers { get; } public string Name { get; } public INamedTypeSymbol ContainingType { get; protected set; } protected CodeGenerationSymbol( IAssemblySymbol containingAssembly, INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes, Accessibility declaredAccessibility, DeclarationModifiers modifiers, string name, string documentationCommentXml = null) { this.ContainingAssembly = containingAssembly; this.ContainingType = containingType; _attributes = attributes.NullToEmpty(); this.DeclaredAccessibility = declaredAccessibility; this.Modifiers = modifiers; this.Name = name; _documentationCommentXml = documentationCommentXml; } protected abstract CodeGenerationSymbol Clone(); internal SyntaxAnnotation[] GetAnnotations() { annotationsTable.TryGetValue(this, out var annotations); return annotations ?? Array.Empty<SyntaxAnnotation>(); } internal CodeGenerationSymbol WithAdditionalAnnotations(params SyntaxAnnotation[] annotations) { return annotations.IsNullOrEmpty() ? this : AddAnnotationsTo(this, this.Clone(), annotations); } private static CodeGenerationSymbol AddAnnotationsTo( CodeGenerationSymbol originalDefinition, CodeGenerationSymbol newDefinition, SyntaxAnnotation[] annotations) { annotationsTable.TryGetValue(originalDefinition, out var originalAnnotations); annotations = SyntaxAnnotationExtensions.CombineAnnotations(originalAnnotations, annotations); annotationsTable.Add(newDefinition, annotations); return newDefinition; } public abstract SymbolKind Kind { get; } public string Language => "Code Generation Agnostic Language"; public virtual ISymbol ContainingSymbol => null; public IAssemblySymbol ContainingAssembly { get; } public static IMethodSymbol ContainingMethod => null; public IModuleSymbol ContainingModule => null; public INamespaceSymbol ContainingNamespace => null; public bool IsDefinition => true; public bool IsStatic { get { return this.Modifiers.IsStatic; } } public bool IsVirtual { get { return this.Modifiers.IsVirtual; } } public bool IsOverride { get { return this.Modifiers.IsOverride; } } public bool IsAbstract { get { return this.Modifiers.IsAbstract; } } public bool IsSealed { get { return this.Modifiers.IsSealed; } } public bool IsExtern => false; public bool IsImplicitlyDeclared => false; public bool CanBeReferencedByName => true; public ImmutableArray<Location> Locations { get { return ImmutableArray.Create<Location>(); } } public static ImmutableArray<SyntaxNode> DeclaringSyntaxNodes { get { return ImmutableArray.Create<SyntaxNode>(); } } public ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray.Create<SyntaxReference>(); } } public ImmutableArray<AttributeData> GetAttributes() => _attributes; public ImmutableArray<AttributeData> GetAttributes(INamedTypeSymbol attributeType) => GetAttributes().WhereAsArray(a => a.AttributeClass.Equals(attributeType)); public ImmutableArray<AttributeData> GetAttributes(IMethodSymbol attributeConstructor) => GetAttributes().WhereAsArray(a => a.AttributeConstructor.Equals(attributeConstructor)); public ISymbol OriginalDefinition { get { return this; } } public abstract void Accept(SymbolVisitor visitor); public abstract TResult Accept<TResult>(SymbolVisitor<TResult> visitor); public string GetDocumentationCommentId() => null; public string GetDocumentationCommentXml( CultureInfo preferredCulture, bool expandIncludes, CancellationToken cancellationToken) { return _documentationCommentXml ?? ""; } public string ToDisplayString(SymbolDisplayFormat format = null) => throw new NotImplementedException(); public ImmutableArray<SymbolDisplayPart> ToDisplayParts(SymbolDisplayFormat format = null) => throw new NotImplementedException(); public string ToMinimalDisplayString(SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) => throw new NotImplementedException(); public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) => throw new NotImplementedException(); public virtual string MetadataName { get { return this.Name; } } public bool HasUnsupportedMetadata => false; public bool Equals(ISymbol other) => this.Equals((object)other); public bool Equals(ISymbol other, SymbolEqualityComparer equalityComparer) => this.Equals(other); } }
// Licensed to the .NET Foundation under one or more 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.Globalization; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CodeGeneration { internal abstract class CodeGenerationSymbol : ISymbol { protected static ConditionalWeakTable<CodeGenerationSymbol, SyntaxAnnotation[]> annotationsTable = new(); private ImmutableArray<AttributeData> _attributes; protected readonly string _documentationCommentXml; public Accessibility DeclaredAccessibility { get; } protected internal DeclarationModifiers Modifiers { get; } public string Name { get; } public INamedTypeSymbol ContainingType { get; protected set; } protected CodeGenerationSymbol( IAssemblySymbol containingAssembly, INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes, Accessibility declaredAccessibility, DeclarationModifiers modifiers, string name, string documentationCommentXml = null) { this.ContainingAssembly = containingAssembly; this.ContainingType = containingType; _attributes = attributes.NullToEmpty(); this.DeclaredAccessibility = declaredAccessibility; this.Modifiers = modifiers; this.Name = name; _documentationCommentXml = documentationCommentXml; } protected abstract CodeGenerationSymbol Clone(); internal SyntaxAnnotation[] GetAnnotations() { annotationsTable.TryGetValue(this, out var annotations); return annotations ?? Array.Empty<SyntaxAnnotation>(); } internal CodeGenerationSymbol WithAdditionalAnnotations(params SyntaxAnnotation[] annotations) { return annotations.IsNullOrEmpty() ? this : AddAnnotationsTo(this, this.Clone(), annotations); } private static CodeGenerationSymbol AddAnnotationsTo( CodeGenerationSymbol originalDefinition, CodeGenerationSymbol newDefinition, SyntaxAnnotation[] annotations) { annotationsTable.TryGetValue(originalDefinition, out var originalAnnotations); annotations = SyntaxAnnotationExtensions.CombineAnnotations(originalAnnotations, annotations); annotationsTable.Add(newDefinition, annotations); return newDefinition; } public abstract SymbolKind Kind { get; } public string Language => "Code Generation Agnostic Language"; public virtual ISymbol ContainingSymbol => null; public IAssemblySymbol ContainingAssembly { get; } public static IMethodSymbol ContainingMethod => null; public IModuleSymbol ContainingModule => null; public INamespaceSymbol ContainingNamespace => null; public bool IsDefinition => true; public bool IsStatic { get { return this.Modifiers.IsStatic; } } public bool IsVirtual { get { return this.Modifiers.IsVirtual; } } public bool IsOverride { get { return this.Modifiers.IsOverride; } } public bool IsAbstract { get { return this.Modifiers.IsAbstract; } } public bool IsSealed { get { return this.Modifiers.IsSealed; } } public bool IsExtern => false; public bool IsImplicitlyDeclared => false; public bool CanBeReferencedByName => true; public ImmutableArray<Location> Locations { get { return ImmutableArray.Create<Location>(); } } public static ImmutableArray<SyntaxNode> DeclaringSyntaxNodes { get { return ImmutableArray.Create<SyntaxNode>(); } } public ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray.Create<SyntaxReference>(); } } public ImmutableArray<AttributeData> GetAttributes() => _attributes; public ImmutableArray<AttributeData> GetAttributes(INamedTypeSymbol attributeType) => GetAttributes().WhereAsArray(a => a.AttributeClass.Equals(attributeType)); public ImmutableArray<AttributeData> GetAttributes(IMethodSymbol attributeConstructor) => GetAttributes().WhereAsArray(a => a.AttributeConstructor.Equals(attributeConstructor)); public ISymbol OriginalDefinition { get { return this; } } public abstract void Accept(SymbolVisitor visitor); public abstract TResult Accept<TResult>(SymbolVisitor<TResult> visitor); public string GetDocumentationCommentId() => null; public string GetDocumentationCommentXml( CultureInfo preferredCulture, bool expandIncludes, CancellationToken cancellationToken) { return _documentationCommentXml ?? ""; } public string ToDisplayString(SymbolDisplayFormat format = null) => throw new NotImplementedException(); public ImmutableArray<SymbolDisplayPart> ToDisplayParts(SymbolDisplayFormat format = null) => throw new NotImplementedException(); public string ToMinimalDisplayString(SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) => throw new NotImplementedException(); public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) => throw new NotImplementedException(); public virtual string MetadataName { get { return this.Name; } } public bool HasUnsupportedMetadata => false; public bool Equals(ISymbol other) => this.Equals((object)other); public bool Equals(ISymbol other, SymbolEqualityComparer equalityComparer) => this.Equals(other); } }
-1
dotnet/roslyn
55,066
Correctly set IsRetargetable for source assemblies
Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
333fred
2021-07-23T00:55:50Z
2021-07-24T00:08:23Z
a3b5d0f87fbdceadf6d3d1b024aca4736e3e079e
c58fbd573ea1ca0273ef3878782baab73d5201c8
Correctly set IsRetargetable for source assemblies. Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptFindUsagesService.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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.ExternalAccess.VSTypeScript { [ExportLanguageService(typeof(IFindUsagesService), InternalLanguageNames.TypeScript), Shared] internal class VSTypeScriptFindUsagesService : IFindUsagesService { private readonly IVSTypeScriptFindUsagesService _underlyingService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptFindUsagesService(IVSTypeScriptFindUsagesService underlyingService) { _underlyingService = underlyingService; } public Task FindReferencesAsync(Document document, int position, IFindUsagesContext context, CancellationToken cancellationToken) => _underlyingService.FindReferencesAsync(document, position, new VSTypeScriptFindUsagesContext(context), cancellationToken); public Task FindImplementationsAsync(Document document, int position, IFindUsagesContext context, CancellationToken cancellationToken) => _underlyingService.FindImplementationsAsync(document, position, new VSTypeScriptFindUsagesContext(context), cancellationToken); private class VSTypeScriptFindUsagesContext : IVSTypeScriptFindUsagesContext { private readonly IFindUsagesContext _context; private readonly Dictionary<VSTypeScriptDefinitionItem, DefinitionItem> _definitionItemMap = new(); public VSTypeScriptFindUsagesContext(IFindUsagesContext context) { _context = context; } public IVSTypeScriptStreamingProgressTracker ProgressTracker => new VSTypeScriptStreamingProgressTracker(_context.ProgressTracker); public ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken) => _context.ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) => _context.SetSearchTitleAsync(title, cancellationToken); private DefinitionItem GetOrCreateDefinitionItem(VSTypeScriptDefinitionItem item) { lock (_definitionItemMap) { if (!_definitionItemMap.TryGetValue(item, out var result)) { result = DefinitionItem.Create( item.Tags, item.DisplayParts, item.SourceSpans, item.NameDisplayParts, item.Properties, item.DisplayableProperties, item.DisplayIfNoReferences); _definitionItemMap.Add(item, result); } return result; } } public ValueTask OnDefinitionFoundAsync(VSTypeScriptDefinitionItem definition, CancellationToken cancellationToken) { var item = GetOrCreateDefinitionItem(definition); return _context.OnDefinitionFoundAsync(item, cancellationToken); } public ValueTask OnReferenceFoundAsync(VSTypeScriptSourceReferenceItem reference, CancellationToken cancellationToken) { var item = GetOrCreateDefinitionItem(reference.Definition); return _context.OnReferenceFoundAsync(new SourceReferenceItem(item, reference.SourceSpan, reference.SymbolUsageInfo), cancellationToken); } } private class VSTypeScriptStreamingProgressTracker : IVSTypeScriptStreamingProgressTracker { private readonly IStreamingProgressTracker _progressTracker; public VSTypeScriptStreamingProgressTracker(IStreamingProgressTracker progressTracker) { _progressTracker = progressTracker; } public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) => _progressTracker.AddItemsAsync(count, cancellationToken); public ValueTask ItemCompletedAsync(CancellationToken cancellationToken) => _progressTracker.ItemCompletedAsync(cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.ExternalAccess.VSTypeScript { [ExportLanguageService(typeof(IFindUsagesService), InternalLanguageNames.TypeScript), Shared] internal class VSTypeScriptFindUsagesService : IFindUsagesService { private readonly IVSTypeScriptFindUsagesService _underlyingService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptFindUsagesService(IVSTypeScriptFindUsagesService underlyingService) { _underlyingService = underlyingService; } public Task FindReferencesAsync(Document document, int position, IFindUsagesContext context, CancellationToken cancellationToken) => _underlyingService.FindReferencesAsync(document, position, new VSTypeScriptFindUsagesContext(context), cancellationToken); public Task FindImplementationsAsync(Document document, int position, IFindUsagesContext context, CancellationToken cancellationToken) => _underlyingService.FindImplementationsAsync(document, position, new VSTypeScriptFindUsagesContext(context), cancellationToken); private class VSTypeScriptFindUsagesContext : IVSTypeScriptFindUsagesContext { private readonly IFindUsagesContext _context; private readonly Dictionary<VSTypeScriptDefinitionItem, DefinitionItem> _definitionItemMap = new(); public VSTypeScriptFindUsagesContext(IFindUsagesContext context) { _context = context; } public IVSTypeScriptStreamingProgressTracker ProgressTracker => new VSTypeScriptStreamingProgressTracker(_context.ProgressTracker); public ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken) => _context.ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) => _context.SetSearchTitleAsync(title, cancellationToken); private DefinitionItem GetOrCreateDefinitionItem(VSTypeScriptDefinitionItem item) { lock (_definitionItemMap) { if (!_definitionItemMap.TryGetValue(item, out var result)) { result = DefinitionItem.Create( item.Tags, item.DisplayParts, item.SourceSpans, item.NameDisplayParts, item.Properties, item.DisplayableProperties, item.DisplayIfNoReferences); _definitionItemMap.Add(item, result); } return result; } } public ValueTask OnDefinitionFoundAsync(VSTypeScriptDefinitionItem definition, CancellationToken cancellationToken) { var item = GetOrCreateDefinitionItem(definition); return _context.OnDefinitionFoundAsync(item, cancellationToken); } public ValueTask OnReferenceFoundAsync(VSTypeScriptSourceReferenceItem reference, CancellationToken cancellationToken) { var item = GetOrCreateDefinitionItem(reference.Definition); return _context.OnReferenceFoundAsync(new SourceReferenceItem(item, reference.SourceSpan, reference.SymbolUsageInfo), cancellationToken); } } private class VSTypeScriptStreamingProgressTracker : IVSTypeScriptStreamingProgressTracker { private readonly IStreamingProgressTracker _progressTracker; public VSTypeScriptStreamingProgressTracker(IStreamingProgressTracker progressTracker) { _progressTracker = progressTracker; } public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) => _progressTracker.AddItemsAsync(count, cancellationToken); public ValueTask ItemCompletedAsync(CancellationToken cancellationToken) => _progressTracker.ItemCompletedAsync(cancellationToken); } } }
-1
dotnet/roslyn
55,066
Correctly set IsRetargetable for source assemblies
Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
333fred
2021-07-23T00:55:50Z
2021-07-24T00:08:23Z
a3b5d0f87fbdceadf6d3d1b024aca4736e3e079e
c58fbd573ea1ca0273ef3878782baab73d5201c8
Correctly set IsRetargetable for source assemblies. Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
./src/Compilers/Core/Portable/ReferenceManager/Compilation_MetadataCache.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public partial class Compilation { /// <summary> /// The list of RetargetingAssemblySymbol objects created for this Compilation. /// RetargetingAssemblySymbols are created when some other compilation references this one, /// but the other references provided are incompatible with it. For example, compilation C1 /// references v1 of Lib.dll and compilation C2 references C1 and v2 of Lib.dll. In this /// case, in context of C2, all types from v1 of Lib.dll leaking through C1 (through method /// signatures, etc.) must be retargeted to the types from v2 of Lib.dll. This is what /// RetargetingAssemblySymbol is responsible for. In the example above, modules in C2 do not /// reference C1.AssemblySymbol, but reference a special RetargetingAssemblySymbol created /// for C1 by ReferenceManager. /// /// WeakReference is used to allow RetargetingAssemblySymbol to be collected when they become unused. /// /// Guarded by <see cref="CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard"/>. /// </summary> private readonly WeakList<IAssemblySymbolInternal> _retargetingAssemblySymbols = new WeakList<IAssemblySymbolInternal>(); /// <summary> /// Adds given retargeting assembly for this compilation into the cache. /// <see cref="CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard"/> must be locked while calling this method. /// </summary> internal void CacheRetargetingAssemblySymbolNoLock(IAssemblySymbolInternal assembly) { _retargetingAssemblySymbols.Add(assembly); } /// <summary> /// Adds cached retargeting symbols into the given list. /// <see cref="CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard"/> must be locked while calling this method. /// </summary> internal void AddRetargetingAssemblySymbolsNoLock<T>(List<T> result) where T : IAssemblySymbolInternal { foreach (var symbol in _retargetingAssemblySymbols) { result.Add((T)symbol); } } // for testing only internal WeakList<IAssemblySymbolInternal> RetargetingAssemblySymbols { get { return _retargetingAssemblySymbols; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public partial class Compilation { /// <summary> /// The list of RetargetingAssemblySymbol objects created for this Compilation. /// RetargetingAssemblySymbols are created when some other compilation references this one, /// but the other references provided are incompatible with it. For example, compilation C1 /// references v1 of Lib.dll and compilation C2 references C1 and v2 of Lib.dll. In this /// case, in context of C2, all types from v1 of Lib.dll leaking through C1 (through method /// signatures, etc.) must be retargeted to the types from v2 of Lib.dll. This is what /// RetargetingAssemblySymbol is responsible for. In the example above, modules in C2 do not /// reference C1.AssemblySymbol, but reference a special RetargetingAssemblySymbol created /// for C1 by ReferenceManager. /// /// WeakReference is used to allow RetargetingAssemblySymbol to be collected when they become unused. /// /// Guarded by <see cref="CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard"/>. /// </summary> private readonly WeakList<IAssemblySymbolInternal> _retargetingAssemblySymbols = new WeakList<IAssemblySymbolInternal>(); /// <summary> /// Adds given retargeting assembly for this compilation into the cache. /// <see cref="CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard"/> must be locked while calling this method. /// </summary> internal void CacheRetargetingAssemblySymbolNoLock(IAssemblySymbolInternal assembly) { _retargetingAssemblySymbols.Add(assembly); } /// <summary> /// Adds cached retargeting symbols into the given list. /// <see cref="CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard"/> must be locked while calling this method. /// </summary> internal void AddRetargetingAssemblySymbolsNoLock<T>(List<T> result) where T : IAssemblySymbolInternal { foreach (var symbol in _retargetingAssemblySymbols) { result.Add((T)symbol); } } // for testing only internal WeakList<IAssemblySymbolInternal> RetargetingAssemblySymbols { get { return _retargetingAssemblySymbols; } } } }
-1
dotnet/roslyn
55,066
Correctly set IsRetargetable for source assemblies
Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
333fred
2021-07-23T00:55:50Z
2021-07-24T00:08:23Z
a3b5d0f87fbdceadf6d3d1b024aca4736e3e079e
c58fbd573ea1ca0273ef3878782baab73d5201c8
Correctly set IsRetargetable for source assemblies. Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
./src/VisualStudio/Core/Def/Implementation/Snippets/AbstractSnippetExpansionClient.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.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.TextManager.Interop; using MSXML; using Roslyn.Utilities; using CommonFormattingHelpers = Microsoft.CodeAnalysis.Editor.Shared.Utilities.CommonFormattingHelpers; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets { internal abstract class AbstractSnippetExpansionClient : ForegroundThreadAffinitizedObject, IVsExpansionClient { /// <summary> /// The name of a snippet field created for caret placement in Full Method Call snippet sessions when the /// invocation has no parameters. /// </summary> private const string PlaceholderSnippetField = "placeholder"; /// <summary> /// A generated random string which is used to identify argument completion snippets from other snippets. /// </summary> private static readonly string s_fullMethodCallDescriptionSentinel = Guid.NewGuid().ToString("N"); private readonly SignatureHelpControllerProvider _signatureHelpControllerProvider; private readonly IEditorCommandHandlerServiceFactory _editorCommandHandlerServiceFactory; protected readonly IVsEditorAdaptersFactoryService EditorAdaptersFactoryService; protected readonly Guid LanguageServiceGuid; protected readonly ITextView TextView; protected readonly ITextBuffer SubjectBuffer; private readonly ImmutableArray<Lazy<ArgumentProvider, OrderableLanguageMetadata>> _allArgumentProviders; private ImmutableArray<ArgumentProvider> _argumentProviders; private bool _indentCaretOnCommit; private int _indentDepth; private bool _earlyEndExpansionHappened; /// <summary> /// Set to <see langword="true"/> when the snippet client registers an event listener for /// <see cref="Controller.ModelUpdated"/>. /// </summary> /// <remarks> /// This field should only be used from the main thread. /// </remarks> private bool _registeredForSignatureHelpEvents; // Writes to this state only occur on the main thread. private readonly State _state = new(); public AbstractSnippetExpansionClient( IThreadingContext threadingContext, Guid languageServiceGuid, ITextView textView, ITextBuffer subjectBuffer, SignatureHelpControllerProvider signatureHelpControllerProvider, IEditorCommandHandlerServiceFactory editorCommandHandlerServiceFactory, IVsEditorAdaptersFactoryService editorAdaptersFactoryService, ImmutableArray<Lazy<ArgumentProvider, OrderableLanguageMetadata>> argumentProviders) : base(threadingContext) { this.LanguageServiceGuid = languageServiceGuid; this.TextView = textView; this.SubjectBuffer = subjectBuffer; _signatureHelpControllerProvider = signatureHelpControllerProvider; _editorCommandHandlerServiceFactory = editorCommandHandlerServiceFactory; this.EditorAdaptersFactoryService = editorAdaptersFactoryService; _allArgumentProviders = argumentProviders; } /// <inheritdoc cref="State._expansionSession"/> public IVsExpansionSession? ExpansionSession => _state._expansionSession; /// <inheritdoc cref="State.IsFullMethodCallSnippet"/> public bool IsFullMethodCallSnippet => _state.IsFullMethodCallSnippet; public ImmutableArray<ArgumentProvider> GetArgumentProviders(Workspace workspace) { AssertIsForeground(); // TODO: Move this to ArgumentProviderService: https://github.com/dotnet/roslyn/issues/50897 if (_argumentProviders.IsDefault) { _argumentProviders = workspace.Services .SelectMatchingExtensionValues(ExtensionOrderer.Order(_allArgumentProviders), SubjectBuffer.ContentType) .ToImmutableArray(); } return _argumentProviders; } public abstract int GetExpansionFunction(IXMLDOMNode xmlFunctionNode, string bstrFieldName, out IVsExpansionFunction? pFunc); protected abstract ITrackingSpan? InsertEmptyCommentAndGetEndPositionTrackingSpan(); internal abstract Document AddImports(Document document, int position, XElement snippetNode, bool placeSystemNamespaceFirst, bool allowInHiddenRegions, CancellationToken cancellationToken); protected abstract string FallbackDefaultLiteral { get; } public int FormatSpan(IVsTextLines pBuffer, VsTextSpan[] tsInSurfaceBuffer) { AssertIsForeground(); if (ExpansionSession == null) { return VSConstants.E_FAIL; } // If this is a manually-constructed snippet for a full method call, avoid formatting the snippet since // doing so will disrupt signature help. Check ExpansionSession instead of '_state.IsFullMethodCallSnippet' // because '_state._methodNameForInsertFullMethodCall' is not initialized at this point. if (ExpansionSession.TryGetHeaderNode("Description", out var descriptionNode) && descriptionNode?.text == s_fullMethodCallDescriptionSentinel) { return VSConstants.S_OK; } // Formatting a snippet isn't cancellable. var cancellationToken = CancellationToken.None; // At this point, the $selection$ token has been replaced with the selected text and // declarations have been replaced with their default text. We need to format the // inserted snippet text while carefully handling $end$ position (where the caret goes // after Return is pressed). The IVsExpansionSession keeps a tracking point for this // position but we do the tracking ourselves to properly deal with virtual space. To // ensure the end location is correct, we take three extra steps: // 1. Insert an empty comment ("/**/" or "'") at the current $end$ position (prior // to formatting), and keep a tracking span for the comment. // 2. After formatting the new snippet text, find and delete the empty multiline // comment (via the tracking span) and notify the IVsExpansionSession of the new // $end$ location. If the line then contains only whitespace (due to the formatter // putting the empty comment on its own line), then delete the white space and // remember the indentation depth for that line. // 3. When the snippet is finally completed (via Return), and PositionCaretForEditing() // is called, check to see if the end location was on a line containing only white // space in the previous step. If so, and if that line is still empty, then position // the caret in virtual space. // This technique ensures that a snippet like "if($condition$) { $end$ }" will end up // as: // if ($condition$) // { // $end$ // } if (!TryGetSubjectBufferSpan(tsInSurfaceBuffer[0], out var snippetSpan)) { return VSConstants.S_OK; } // Insert empty comment and track end position var snippetTrackingSpan = snippetSpan.CreateTrackingSpan(SpanTrackingMode.EdgeInclusive); var fullSnippetSpan = new VsTextSpan[1]; ExpansionSession.GetSnippetSpan(fullSnippetSpan); var isFullSnippetFormat = fullSnippetSpan[0].iStartLine == tsInSurfaceBuffer[0].iStartLine && fullSnippetSpan[0].iStartIndex == tsInSurfaceBuffer[0].iStartIndex && fullSnippetSpan[0].iEndLine == tsInSurfaceBuffer[0].iEndLine && fullSnippetSpan[0].iEndIndex == tsInSurfaceBuffer[0].iEndIndex; var endPositionTrackingSpan = isFullSnippetFormat ? InsertEmptyCommentAndGetEndPositionTrackingSpan() : null; var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(SubjectBuffer.CurrentSnapshot, snippetTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot)); SubjectBuffer.CurrentSnapshot.FormatAndApplyToBuffer(formattingSpan, CancellationToken.None); if (isFullSnippetFormat) { CleanUpEndLocation(endPositionTrackingSpan); // Unfortunately, this is the only place we can safely add references and imports // specified in the snippet xml. In OnBeforeInsertion we have no guarantee that the // snippet xml will be available, and changing the buffer during OnAfterInsertion can // cause the underlying tracking spans to get out of sync. var currentStartPosition = snippetTrackingSpan.GetStartPoint(SubjectBuffer.CurrentSnapshot).Position; AddReferencesAndImports( ExpansionSession, currentStartPosition, cancellationToken); SetNewEndPosition(endPositionTrackingSpan); } return VSConstants.S_OK; } private void SetNewEndPosition(ITrackingSpan? endTrackingSpan) { RoslynDebug.AssertNotNull(ExpansionSession); if (SetEndPositionIfNoneSpecified(ExpansionSession)) { return; } if (endTrackingSpan != null) { if (!TryGetSpanOnHigherBuffer( endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot), TextView.TextBuffer, out var endSpanInSurfaceBuffer)) { return; } TextView.TextSnapshot.GetLineAndCharacter(endSpanInSurfaceBuffer.Start.Position, out var endLine, out var endChar); ExpansionSession.SetEndSpan(new VsTextSpan { iStartLine = endLine, iStartIndex = endChar, iEndLine = endLine, iEndIndex = endChar }); } } private void CleanUpEndLocation(ITrackingSpan? endTrackingSpan) { if (endTrackingSpan != null) { // Find the empty comment and remove it... var endSnapshotSpan = endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot); SubjectBuffer.Delete(endSnapshotSpan.Span); // Remove the whitespace before the comment if necessary. If whitespace is removed, // then remember the indentation depth so we can appropriately position the caret // in virtual space when the session is ended. var line = SubjectBuffer.CurrentSnapshot.GetLineFromPosition(endSnapshotSpan.Start.Position); var lineText = line.GetText(); if (lineText.Trim() == string.Empty) { _indentCaretOnCommit = true; var document = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var documentOptions = document.GetOptionsAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); _indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, documentOptions.GetOption(FormattingOptions.TabSize)); } else { // If we don't have a document, then just guess the typical default TabSize value. _indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, tabSize: 4); } SubjectBuffer.Delete(new Span(line.Start.Position, line.Length)); _ = SubjectBuffer.CurrentSnapshot.GetSpan(new Span(line.Start.Position, 0)); } } } /// <summary> /// If there was no $end$ token, place it at the end of the snippet code. Otherwise, it /// defaults to the beginning of the snippet code. /// </summary> private static bool SetEndPositionIfNoneSpecified(IVsExpansionSession pSession) { if (!TryGetSnippetNode(pSession, out var snippetNode)) { return false; } var ns = snippetNode.Name.NamespaceName; var codeNode = snippetNode.Element(XName.Get("Code", ns)); if (codeNode == null) { return false; } var delimiterAttribute = codeNode.Attribute("Delimiter"); var delimiter = delimiterAttribute != null ? delimiterAttribute.Value : "$"; if (codeNode.Value.IndexOf(string.Format("{0}end{0}", delimiter), StringComparison.OrdinalIgnoreCase) != -1) { return false; } var snippetSpan = new VsTextSpan[1]; if (pSession.GetSnippetSpan(snippetSpan) != VSConstants.S_OK) { return false; } var newEndSpan = new VsTextSpan { iStartLine = snippetSpan[0].iEndLine, iStartIndex = snippetSpan[0].iEndIndex, iEndLine = snippetSpan[0].iEndLine, iEndIndex = snippetSpan[0].iEndIndex }; pSession.SetEndSpan(newEndSpan); return true; } protected static bool TryGetSnippetNode(IVsExpansionSession pSession, [NotNullWhen(true)] out XElement? snippetNode) { IXMLDOMNode? xmlNode = null; snippetNode = null; try { // Cast to our own version of IVsExpansionSession so that we can get pNode as an // IntPtr instead of a via a RCW. This allows us to guarantee that it pNode is // released before leaving this method. Otherwise, a second invocation of the same // snippet may cause an AccessViolationException. var session = (IVsExpansionSessionInternal)pSession; if (session.GetSnippetNode(null, out var pNode) != VSConstants.S_OK) { return false; } xmlNode = (IXMLDOMNode)Marshal.GetUniqueObjectForIUnknown(pNode); snippetNode = XElement.Parse(xmlNode.xml); return true; } finally { if (xmlNode != null && Marshal.IsComObject(xmlNode)) { Marshal.ReleaseComObject(xmlNode); } } } public int PositionCaretForEditing(IVsTextLines pBuffer, [ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")] VsTextSpan[] ts) { // If the formatted location of the $end$ position (the inserted comment) was on an // empty line and indented, then we have already removed the white space on that line // and the navigation location will be at column 0 on a blank line. We must now // position the caret in virtual space. pBuffer.GetLengthOfLine(ts[0].iStartLine, out var lineLength); pBuffer.GetLineText(ts[0].iStartLine, 0, ts[0].iStartLine, lineLength, out var endLineText); pBuffer.GetPositionOfLine(ts[0].iStartLine, out var endLinePosition); PositionCaretForEditingInternal(endLineText, endLinePosition); return VSConstants.S_OK; } /// <summary> /// Internal for testing purposes. All real caret positioning logic takes place here. <see cref="PositionCaretForEditing"/> /// only extracts the <paramref name="endLineText"/> and <paramref name="endLinePosition"/> from the provided <see cref="IVsTextLines"/>. /// Tests can call this method directly to avoid producing an IVsTextLines. /// </summary> /// <param name="endLineText"></param> /// <param name="endLinePosition"></param> internal void PositionCaretForEditingInternal(string endLineText, int endLinePosition) { if (_indentCaretOnCommit && endLineText == string.Empty) { TextView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(TextView.TextSnapshot.GetPoint(endLinePosition), _indentDepth)); } } public virtual bool TryHandleTab() { if (ExpansionSession != null) { // When 'Tab' is pressed in the last field of a normal snippet, the session wraps back around to the // first field (this is preservation of historical behavior). When 'Tab' is pressed at the end of an // argument provider snippet, the snippet session is automatically committed (this behavior matches the // design for Insert Full Method Call intended for multiple IDEs). var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(fCommitIfLast: _state.IsFullMethodCallSnippet ? 1 : 0); if (!tabbedInsideSnippetField) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); } return tabbedInsideSnippetField; } return false; } public virtual bool TryHandleBackTab() { if (ExpansionSession != null) { var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToPreviousExpansionField(); if (!tabbedInsideSnippetField) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); } return tabbedInsideSnippetField; } return false; } public virtual bool TryHandleEscape() { if (ExpansionSession != null) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); return true; } return false; } public virtual bool TryHandleReturn() { return CommitSnippet(leaveCaret: false); } /// <summary> /// Commit the active snippet, if any. /// </summary> /// <param name="leaveCaret"><see langword="true"/> to leave the caret position unchanged by the call; /// otherwise, <see langword="false"/> to move the caret to the <c>$end$</c> position of the snippet when the /// snippet is committed.</param> /// <returns><see langword="true"/> if the caret may have moved from the call; otherwise, /// <see langword="false"/> if the caret did not move, or if there was no active snippet session to /// commit.</returns> public bool CommitSnippet(bool leaveCaret) { if (ExpansionSession != null) { if (!leaveCaret) { // Only move the caret if the enter was hit within the snippet fields. var hitWithinField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(fCommitIfLast: 0); leaveCaret = !hitWithinField; } ExpansionSession.EndCurrentExpansion(fLeaveCaret: leaveCaret ? 1 : 0); return !leaveCaret; } return false; } public virtual bool TryInsertExpansion(int startPositionInSubjectBuffer, int endPositionInSubjectBuffer, CancellationToken cancellationToken) { var textViewModel = TextView.TextViewModel; if (textViewModel == null) { Debug.Assert(TextView.IsClosed); return false; } // The expansion itself needs to be created in the data buffer, so map everything up var triggerSpan = SubjectBuffer.CurrentSnapshot.GetSpan(startPositionInSubjectBuffer, endPositionInSubjectBuffer - startPositionInSubjectBuffer); if (!TryGetSpanOnHigherBuffer(triggerSpan, textViewModel.DataBuffer, out var dataBufferSpan)) { return false; } var buffer = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer); if (buffer is not IVsExpansion expansion) { return false; } buffer.GetLineIndexOfPosition(dataBufferSpan.Start.Position, out var startLine, out var startIndex); buffer.GetLineIndexOfPosition(dataBufferSpan.End.Position, out var endLine, out var endIndex); var textSpan = new VsTextSpan { iStartLine = startLine, iStartIndex = startIndex, iEndLine = endLine, iEndIndex = endIndex }; if (TryInsertArgumentCompletionSnippet(triggerSpan, dataBufferSpan, expansion, textSpan, cancellationToken)) { Debug.Assert(_state.IsFullMethodCallSnippet); return true; } if (expansion.InsertExpansion(textSpan, textSpan, this, LanguageServiceGuid, out _state._expansionSession) == VSConstants.S_OK) { // This expansion is not derived from a symbol, so make sure the state isn't tracking any symbol // information Debug.Assert(!_state.IsFullMethodCallSnippet); return true; } return false; } private bool TryInsertArgumentCompletionSnippet(SnapshotSpan triggerSpan, SnapshotSpan dataBufferSpan, IVsExpansion expansion, VsTextSpan textSpan, CancellationToken cancellationToken) { if (!(SubjectBuffer.GetFeatureOnOffOption(CompletionOptions.EnableArgumentCompletionSnippets) ?? false)) { // Argument completion snippets are not enabled return false; } var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document is null) { // Couldn't identify the current document return false; } var symbols = ThreadingContext.JoinableTaskFactory.Run(() => GetReferencedSymbolsToLeftOfCaretAsync(document, caretPosition: triggerSpan.End, cancellationToken)); var methodSymbols = symbols.OfType<IMethodSymbol>().ToImmutableArray(); if (methodSymbols.Any()) { // This is the method name as it appears in source text var methodName = dataBufferSpan.GetText(); var snippet = CreateMethodCallSnippet(methodName, includeMethod: true, ImmutableArray<IParameterSymbol>.Empty, ImmutableDictionary<string, string>.Empty); var doc = (DOMDocument)new DOMDocumentClass(); if (doc.loadXML(snippet.ToString(SaveOptions.OmitDuplicateNamespaces))) { if (expansion.InsertSpecificExpansion(doc, textSpan, this, LanguageServiceGuid, pszRelativePath: null, out _state._expansionSession) == VSConstants.S_OK) { Debug.Assert(_state._expansionSession != null); _state._methodNameForInsertFullMethodCall = methodSymbols.First().Name; Debug.Assert(_state._method == null); if (_signatureHelpControllerProvider.GetController(TextView, SubjectBuffer) is { } controller) { EnsureRegisteredForModelUpdatedEvents(this, controller); } // Trigger signature help after starting the snippet session // // TODO: Figure out why ISignatureHelpBroker.TriggerSignatureHelp doesn't work but this does. // https://github.com/dotnet/roslyn/issues/50036 var editorCommandHandlerService = _editorCommandHandlerServiceFactory.GetService(TextView, SubjectBuffer); editorCommandHandlerService.Execute((view, buffer) => new InvokeSignatureHelpCommandArgs(view, buffer), nextCommandHandler: null); return true; } } } return false; // Local function static void EnsureRegisteredForModelUpdatedEvents(AbstractSnippetExpansionClient client, Controller controller) { // Access to _registeredForSignatureHelpEvents is synchronized on the main thread client.ThreadingContext.ThrowIfNotOnUIThread(); if (!client._registeredForSignatureHelpEvents) { client._registeredForSignatureHelpEvents = true; controller.ModelUpdated += client.OnModelUpdated; client.TextView.Closed += delegate { controller.ModelUpdated -= client.OnModelUpdated; }; } } } /// <summary> /// Creates a snippet for providing arguments to a call. /// </summary> /// <param name="methodName">The name of the method as it should appear in code.</param> /// <param name="includeMethod"> /// <para><see langword="true"/> to include the method name and invocation parentheses in the resulting snippet; /// otherwise, <see langword="false"/> if the method name and parentheses are assumed to already exist and the /// template will only specify the argument placeholders. Since the <c>$end$</c> marker is always considered to /// lie after the closing <c>)</c> of the invocation, it is only included when this parameter is /// <see langword="true"/>.</para> /// /// <para>For example, consider a call to <see cref="int.ToString(IFormatProvider)"/>. If /// <paramref name="includeMethod"/> is <see langword="true"/>, the resulting snippet text might look like /// this:</para> /// /// <code> /// ToString($provider$)$end$ /// </code> /// /// <para>If <paramref name="includeMethod"/> is <see langword="false"/>, the resulting snippet text might look /// like this:</para> /// /// <code> /// $provider$ /// </code> /// /// <para>This parameter supports cycling between overloads of a method for argument completion. Since any text /// edit that alters the <c>(</c> or <c>)</c> characters will force the Signature Help session to close, we are /// careful to only update text that lies between these characters.</para> /// </param> /// <param name="parameters">The parameters to the method. If the specific target of the invocation is not /// known, an empty array may be passed to create a template with a placeholder where arguments will eventually /// go.</param> private static XDocument CreateMethodCallSnippet(string methodName, bool includeMethod, ImmutableArray<IParameterSymbol> parameters, ImmutableDictionary<string, string> parameterValues) { XNamespace snippetNamespace = "http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"; var template = new StringBuilder(); if (includeMethod) { template.Append(methodName).Append('('); } var declarations = new List<XElement>(); foreach (var parameter in parameters) { if (declarations.Any()) { template.Append(", "); } // Create a snippet field for the argument. The name of the field matches the parameter name, and the // default value for the field is provided by a call to the internal ArgumentValue snippet function. The // parameter to the snippet function is a serialized SymbolKey which can be mapped back to the // IParameterSymbol. template.Append('$').Append(parameter.Name).Append('$'); declarations.Add(new XElement( snippetNamespace + "Literal", new XElement(snippetNamespace + "ID", new XText(parameter.Name)), new XElement(snippetNamespace + "Default", new XText(parameterValues.GetValueOrDefault(parameter.Name, ""))))); } if (!declarations.Any()) { // If the invocation does not have any parameters, include an empty placeholder in the snippet template // to ensure the caret starts inside the parentheses and can track changes to other overloads (which may // have parameters). template.Append($"${PlaceholderSnippetField}$"); declarations.Add(new XElement( snippetNamespace + "Literal", new XElement(snippetNamespace + "ID", new XText(PlaceholderSnippetField)), new XElement(snippetNamespace + "Default", new XText("")))); } if (includeMethod) { template.Append(')'); } template.Append("$end$"); // A snippet is manually constructed. Replacement fields are added for each argument, and the field name // matches the parameter name. // https://docs.microsoft.com/en-us/visualstudio/ide/code-snippets-schema-reference?view=vs-2019 return new XDocument( new XDeclaration("1.0", "utf-8", null), new XElement( snippetNamespace + "CodeSnippets", new XElement( snippetNamespace + "CodeSnippet", new XAttribute(snippetNamespace + "Format", "1.0.0"), new XElement( snippetNamespace + "Header", new XElement(snippetNamespace + "Title", new XText(methodName)), new XElement(snippetNamespace + "Description", new XText(s_fullMethodCallDescriptionSentinel))), new XElement( snippetNamespace + "Snippet", new XElement(snippetNamespace + "Declarations", declarations.ToArray()), new XElement( snippetNamespace + "Code", new XAttribute(snippetNamespace + "Language", "csharp"), new XCData(template.ToString())))))); } private void OnModelUpdated(object sender, ModelUpdatedEventsArgs e) { AssertIsForeground(); if (e.NewModel is null) { // Signature Help was dismissed, but it's possible for a user to bring it back with Ctrl+Shift+Space. // Leave the snippet session (if any) in its current state to allow it to process either a subsequent // Signature Help update or the Escape/Enter keys that close the snippet session. return; } if (!_state.IsFullMethodCallSnippet) { // Signature Help is showing an updated signature, but either there is no active snippet, or the active // snippet is not performing argument value completion, so we just ignore it. return; } if (!e.NewModel.UserSelected && _state._method is not null) { // This was an implicit signature change which was not triggered by user pressing up/down, and we are // already showing an initialized argument completion snippet session, so avoid switching sessions. return; } var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document is null) { // It's unclear if/how this state would occur, but if it does we would throw an exception trying to // use it. Just return immediately. return; } // TODO: The following blocks the UI thread without cancellation, but it only occurs when an argument value // completion session is active, which is behind an experimental feature flag. // https://github.com/dotnet/roslyn/issues/50634 var compilation = ThreadingContext.JoinableTaskFactory.Run(() => document.Project.GetRequiredCompilationAsync(CancellationToken.None)); var newSymbolKey = (e.NewModel.SelectedItem as AbstractSignatureHelpProvider.SymbolKeySignatureHelpItem)?.SymbolKey ?? default; var newSymbol = newSymbolKey.Resolve(compilation, cancellationToken: CancellationToken.None).GetAnySymbol(); if (newSymbol is not IMethodSymbol method) return; MoveToSpecificMethod(method, CancellationToken.None); } private static async Task<ImmutableArray<ISymbol>> GetReferencedSymbolsToLeftOfCaretAsync( Document document, SnapshotPoint caretPosition, CancellationToken cancellationToken) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var token = await semanticModel.SyntaxTree.GetTouchingWordAsync(caretPosition.Position, document.GetRequiredLanguageService<ISyntaxFactsService>(), cancellationToken).ConfigureAwait(false); if (token.RawKind == 0) { // There is no touching word, so return empty immediately return ImmutableArray<ISymbol>.Empty; } var semanticInfo = semanticModel.GetSemanticInfo(token, document.Project.Solution.Workspace, cancellationToken); return semanticInfo.ReferencedSymbols; } /// <summary> /// Update the current argument value completion session to use a specific method. /// </summary> /// <param name="method">The currently-selected method in Signature Help.</param> /// <param name="cancellationToken">A cancellation token the operation may observe.</param> public void MoveToSpecificMethod(IMethodSymbol method, CancellationToken cancellationToken) { AssertIsForeground(); if (ExpansionSession is null) { return; } if (SymbolEquivalenceComparer.Instance.Equals(_state._method, method)) { return; } if (_state._methodNameForInsertFullMethodCall != method.Name) { // Signature Help is showing a signature that wasn't part of the set this argument value completion // session was created from. It's unclear how this state should be handled, so we stop processing // Signature Help updates for the current session. // TODO: https://github.com/dotnet/roslyn/issues/50636 ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); return; } // If the first method overload chosen is a zero-parameter method, the snippet we'll create is the same snippet // as the one did initially. The editor appears to have a bug where inserting a zero-width snippet (when we update the parameters) // causes the inserted session to immediately dismiss; this works around that issue. if (_state._method is null && method.Parameters.Length == 0) { _state._method = method; return; } var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document is null) { // Couldn't identify the current document ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); return; } var textViewModel = TextView.TextViewModel; if (textViewModel == null) { Debug.Assert(TextView.IsClosed); return; } var buffer = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer); if (buffer is not IVsExpansion expansion) { return; } // We need to replace the portion of the existing Full Method Call snippet which appears inside parentheses. // This span starts at the beginning of the first snippet field, and ends at the end of the last snippet // field. Methods with no arguments still have an empty "placeholder" snippet field representing the initial // caret position when the snippet is created. var textSpan = new VsTextSpan[1]; if (ExpansionSession.GetSnippetSpan(textSpan) != VSConstants.S_OK) { return; } var firstField = _state._method?.Parameters.FirstOrDefault()?.Name ?? PlaceholderSnippetField; if (ExpansionSession.GetFieldSpan(firstField, textSpan) != VSConstants.S_OK) { return; } VsTextSpan adjustedTextSpan; adjustedTextSpan.iStartLine = textSpan[0].iStartLine; adjustedTextSpan.iStartIndex = textSpan[0].iStartIndex; var lastField = _state._method?.Parameters.LastOrDefault()?.Name ?? PlaceholderSnippetField; if (ExpansionSession.GetFieldSpan(lastField, textSpan) != VSConstants.S_OK) { return; } adjustedTextSpan.iEndLine = textSpan[0].iEndLine; adjustedTextSpan.iEndIndex = textSpan[0].iEndIndex; // Track current argument values so input created/updated by a user is not lost when cycling through // Signature Help overloads: // // 1. For each parameter of the method currently presented as a snippet, the value of the argument as // it appears in code. // 2. Place the argument values in a map from parameter name to current value. // 3. (Later) the values in the map can be read to avoid providing new values for equivalent parameters. var newArguments = _state._arguments; if (_state._method is null || !_state._method.Parameters.Any()) { // If we didn't have any previous parameters, then there is only the placeholder in the snippet. // We don't want to lose what the user has typed there, if they typed something if (ExpansionSession.GetFieldValue(PlaceholderSnippetField, out var placeholderValue) == VSConstants.S_OK && placeholderValue.Length > 0) { if (method.Parameters.Any()) { newArguments = newArguments.SetItem(method.Parameters[0].Name, placeholderValue); } else { // TODO: if the user is typing before signature help updated the model, and we have no parameters here, // should we still create a new snippet that has the existing placeholder text? } } } else if (_state._method is not null) { foreach (var previousParameter in _state._method.Parameters) { if (ExpansionSession.GetFieldValue(previousParameter.Name, out var previousValue) == VSConstants.S_OK) { newArguments = newArguments.SetItem(previousParameter.Name, previousValue); } } } // Now compute the new arguments for the new call var semanticModel = document.GetRequiredSemanticModelAsync(cancellationToken).AsTask().WaitAndGetResult(cancellationToken); var position = SubjectBuffer.CurrentSnapshot.GetPosition(adjustedTextSpan.iStartLine, adjustedTextSpan.iStartIndex); foreach (var parameter in method.Parameters) { newArguments.TryGetValue(parameter.Name, out var value); foreach (var provider in GetArgumentProviders(document.Project.Solution.Workspace)) { var context = new ArgumentContext(provider, semanticModel, position, parameter, value, cancellationToken); ThreadingContext.JoinableTaskFactory.Run(() => provider.ProvideArgumentAsync(context)); if (context.DefaultValue is not null) { value = context.DefaultValue; break; } } // If we still have no value, fill in the default if (value is null) { value = FallbackDefaultLiteral; } newArguments = newArguments.SetItem(parameter.Name, value); } var snippet = CreateMethodCallSnippet(method.Name, includeMethod: false, method.Parameters, newArguments); var doc = (DOMDocument)new DOMDocumentClass(); if (doc.loadXML(snippet.ToString(SaveOptions.OmitDuplicateNamespaces))) { if (expansion.InsertSpecificExpansion(doc, adjustedTextSpan, this, LanguageServiceGuid, pszRelativePath: null, out _state._expansionSession) == VSConstants.S_OK) { Debug.Assert(_state._expansionSession != null); _state._methodNameForInsertFullMethodCall = method.Name; _state._method = method; _state._arguments = newArguments; // On this path, the closing parenthesis is not part of the updated snippet, so there is no way for // the snippet itself to represent the $end$ marker (which falls after the ')' character). Instead, // we use the internal APIs to manually specify the effective position of the $end$ marker as the // location in code immediately following the ')'. To do this, we use the knowledge that the snippet // includes all text up to (but not including) the ')', and move that span one position to the // right. if (ExpansionSession.GetEndSpan(textSpan) == VSConstants.S_OK) { textSpan[0].iStartIndex++; textSpan[0].iEndIndex++; ExpansionSession.SetEndSpan(textSpan[0]); } } } } public int EndExpansion() { if (ExpansionSession == null) { _earlyEndExpansionHappened = true; } _state.Clear(); _indentCaretOnCommit = false; return VSConstants.S_OK; } public int IsValidKind(IVsTextLines pBuffer, VsTextSpan[] ts, string bstrKind, out int pfIsValidKind) { pfIsValidKind = 1; return VSConstants.S_OK; } public int IsValidType(IVsTextLines pBuffer, VsTextSpan[] ts, string[] rgTypes, int iCountTypes, out int pfIsValidType) { pfIsValidType = 1; return VSConstants.S_OK; } public int OnAfterInsertion(IVsExpansionSession pSession) { Logger.Log(FunctionId.Snippet_OnAfterInsertion); return VSConstants.S_OK; } public int OnBeforeInsertion(IVsExpansionSession pSession) { Logger.Log(FunctionId.Snippet_OnBeforeInsertion); _state._expansionSession = pSession; // Symbol information (when necessary) is set by the caller return VSConstants.S_OK; } public int OnItemChosen(string pszTitle, string pszPath) { var textViewModel = TextView.TextViewModel; if (textViewModel == null) { Debug.Assert(TextView.IsClosed); return VSConstants.E_FAIL; } int hr; try { VsTextSpan textSpan; GetCaretPositionInSurfaceBuffer(out textSpan.iStartLine, out textSpan.iStartIndex); textSpan.iEndLine = textSpan.iStartLine; textSpan.iEndIndex = textSpan.iStartIndex; var expansion = (IVsExpansion?)EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer); Contract.ThrowIfNull(expansion); _earlyEndExpansionHappened = false; hr = expansion.InsertNamedExpansion(pszTitle, pszPath, textSpan, this, LanguageServiceGuid, fShowDisambiguationUI: 0, pSession: out _state._expansionSession); if (_earlyEndExpansionHappened) { // EndExpansion was called before InsertNamedExpansion returned, so set // expansionSession to null to indicate that there is no active expansion // session. This can occur when the snippet inserted doesn't have any expansion // fields. _state._expansionSession = null; _earlyEndExpansionHappened = false; } } catch (COMException ex) { hr = ex.ErrorCode; } return hr; } private void GetCaretPositionInSurfaceBuffer(out int caretLine, out int caretColumn) { var vsTextView = EditorAdaptersFactoryService.GetViewAdapter(TextView); Contract.ThrowIfNull(vsTextView); vsTextView.GetCaretPos(out caretLine, out caretColumn); vsTextView.GetBuffer(out var textLines); // Handle virtual space (e.g, see Dev10 778675) textLines.GetLengthOfLine(caretLine, out var lineLength); if (caretColumn > lineLength) { caretColumn = lineLength; } } private void AddReferencesAndImports( IVsExpansionSession pSession, int position, CancellationToken cancellationToken) { if (!TryGetSnippetNode(pSession, out var snippetNode)) { return; } var documentWithImports = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (documentWithImports == null) { return; } var documentOptions = documentWithImports.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken); var placeSystemNamespaceFirst = documentOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst); var allowInHiddenRegions = documentWithImports.CanAddImportsInHiddenRegions(); documentWithImports = AddImports(documentWithImports, position, snippetNode, placeSystemNamespaceFirst, allowInHiddenRegions, cancellationToken); AddReferences(documentWithImports.Project, snippetNode); } private void AddReferences(Project originalProject, XElement snippetNode) { var referencesNode = snippetNode.Element(XName.Get("References", snippetNode.Name.NamespaceName)); if (referencesNode == null) { return; } var existingReferenceNames = originalProject.MetadataReferences.Select(r => Path.GetFileNameWithoutExtension(r.Display)); var workspace = originalProject.Solution.Workspace; var projectId = originalProject.Id; var assemblyXmlName = XName.Get("Assembly", snippetNode.Name.NamespaceName); var failedReferenceAdditions = new List<string>(); foreach (var reference in referencesNode.Elements(XName.Get("Reference", snippetNode.Name.NamespaceName))) { // Note: URL references are not supported var assemblyElement = reference.Element(assemblyXmlName); var assemblyName = assemblyElement != null ? assemblyElement.Value.Trim() : null; if (RoslynString.IsNullOrEmpty(assemblyName)) { continue; } if (!(workspace is VisualStudioWorkspaceImpl visualStudioWorkspace) || !visualStudioWorkspace.TryAddReferenceToProject(projectId, assemblyName)) { failedReferenceAdditions.Add(assemblyName); } } if (failedReferenceAdditions.Any()) { var notificationService = workspace.Services.GetRequiredService<INotificationService>(); notificationService.SendNotification( string.Format(ServicesVSResources.The_following_references_were_not_found_0_Please_locate_and_add_them_manually, Environment.NewLine) + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, failedReferenceAdditions), severity: NotificationSeverity.Warning); } } protected static bool TryAddImportsToContainedDocument(Document document, IEnumerable<string> memberImportsNamespaces) { if (!(document.Project.Solution.Workspace is VisualStudioWorkspaceImpl vsWorkspace)) { return false; } var containedDocument = vsWorkspace.TryGetContainedDocument(document.Id); if (containedDocument == null) { return false; } if (containedDocument.ContainedLanguageHost is IVsContainedLanguageHostInternal containedLanguageHost) { foreach (var importClause in memberImportsNamespaces) { if (containedLanguageHost.InsertImportsDirective(importClause) != VSConstants.S_OK) { return false; } } } return true; } protected static bool TryGetSnippetFunctionInfo( IXMLDOMNode xmlFunctionNode, [NotNullWhen(true)] out string? snippetFunctionName, [NotNullWhen(true)] out string? param) { if (xmlFunctionNode.text.IndexOf('(') == -1 || xmlFunctionNode.text.IndexOf(')') == -1 || xmlFunctionNode.text.IndexOf(')') < xmlFunctionNode.text.IndexOf('(')) { snippetFunctionName = null; param = null; return false; } snippetFunctionName = xmlFunctionNode.text.Substring(0, xmlFunctionNode.text.IndexOf('(')); var paramStart = xmlFunctionNode.text.IndexOf('(') + 1; var paramLength = xmlFunctionNode.text.LastIndexOf(')') - xmlFunctionNode.text.IndexOf('(') - 1; param = xmlFunctionNode.text.Substring(paramStart, paramLength); return true; } internal bool TryGetSubjectBufferSpan(VsTextSpan surfaceBufferTextSpan, out SnapshotSpan subjectBufferSpan) { var snapshotSpan = TextView.TextSnapshot.GetSpan(surfaceBufferTextSpan); var subjectBufferSpanCollection = TextView.BufferGraph.MapDownToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, SubjectBuffer); // Bail if a snippet span does not map down to exactly one subject buffer span. if (subjectBufferSpanCollection.Count == 1) { subjectBufferSpan = subjectBufferSpanCollection.Single(); return true; } subjectBufferSpan = default; return false; } internal bool TryGetSpanOnHigherBuffer(SnapshotSpan snapshotSpan, ITextBuffer targetBuffer, out SnapshotSpan span) { var spanCollection = TextView.BufferGraph.MapUpToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, targetBuffer); // Bail if a snippet span does not map up to exactly one span. if (spanCollection.Count == 1) { span = spanCollection.Single(); return true; } span = default; return false; } private sealed class State { /// <summary> /// The current expansion session. /// </summary> public IVsExpansionSession? _expansionSession; /// <summary> /// The symbol name of the method that we have invoked insert full method call on; or <see langword="null"/> /// if there is no active snippet session or the active session is a regular snippets session. /// </summary> public string? _methodNameForInsertFullMethodCall; /// <summary> /// The current symbol presented in an Argument Provider snippet session. This may be null if Signature Help /// has not yet provided a symbol to show. /// </summary> public IMethodSymbol? _method; /// <summary> /// Maps from parameter name to current argument value. When this dictionary does not contain a mapping for /// a parameter, it means no argument has been provided yet by an ArgumentProvider or the user for a /// parameter with this name. This map is cleared at the final end of an argument provider snippet session. /// </summary> public ImmutableDictionary<string, string> _arguments = ImmutableDictionary.Create<string, string>(); /// <summary> /// <see langword="true"/> if the current snippet session is a Full Method Call snippet session; otherwise, /// <see langword="false"/> if there is no current snippet session or if the current snippet session is a normal snippet. /// </summary> public bool IsFullMethodCallSnippet => _expansionSession is not null && _methodNameForInsertFullMethodCall is not null; public void Clear() { _expansionSession = null; _methodNameForInsertFullMethodCall = null; _method = null; _arguments = _arguments.Clear(); } } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.TextManager.Interop; using MSXML; using Roslyn.Utilities; using CommonFormattingHelpers = Microsoft.CodeAnalysis.Editor.Shared.Utilities.CommonFormattingHelpers; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets { internal abstract class AbstractSnippetExpansionClient : ForegroundThreadAffinitizedObject, IVsExpansionClient { /// <summary> /// The name of a snippet field created for caret placement in Full Method Call snippet sessions when the /// invocation has no parameters. /// </summary> private const string PlaceholderSnippetField = "placeholder"; /// <summary> /// A generated random string which is used to identify argument completion snippets from other snippets. /// </summary> private static readonly string s_fullMethodCallDescriptionSentinel = Guid.NewGuid().ToString("N"); private readonly SignatureHelpControllerProvider _signatureHelpControllerProvider; private readonly IEditorCommandHandlerServiceFactory _editorCommandHandlerServiceFactory; protected readonly IVsEditorAdaptersFactoryService EditorAdaptersFactoryService; protected readonly Guid LanguageServiceGuid; protected readonly ITextView TextView; protected readonly ITextBuffer SubjectBuffer; private readonly ImmutableArray<Lazy<ArgumentProvider, OrderableLanguageMetadata>> _allArgumentProviders; private ImmutableArray<ArgumentProvider> _argumentProviders; private bool _indentCaretOnCommit; private int _indentDepth; private bool _earlyEndExpansionHappened; /// <summary> /// Set to <see langword="true"/> when the snippet client registers an event listener for /// <see cref="Controller.ModelUpdated"/>. /// </summary> /// <remarks> /// This field should only be used from the main thread. /// </remarks> private bool _registeredForSignatureHelpEvents; // Writes to this state only occur on the main thread. private readonly State _state = new(); public AbstractSnippetExpansionClient( IThreadingContext threadingContext, Guid languageServiceGuid, ITextView textView, ITextBuffer subjectBuffer, SignatureHelpControllerProvider signatureHelpControllerProvider, IEditorCommandHandlerServiceFactory editorCommandHandlerServiceFactory, IVsEditorAdaptersFactoryService editorAdaptersFactoryService, ImmutableArray<Lazy<ArgumentProvider, OrderableLanguageMetadata>> argumentProviders) : base(threadingContext) { this.LanguageServiceGuid = languageServiceGuid; this.TextView = textView; this.SubjectBuffer = subjectBuffer; _signatureHelpControllerProvider = signatureHelpControllerProvider; _editorCommandHandlerServiceFactory = editorCommandHandlerServiceFactory; this.EditorAdaptersFactoryService = editorAdaptersFactoryService; _allArgumentProviders = argumentProviders; } /// <inheritdoc cref="State._expansionSession"/> public IVsExpansionSession? ExpansionSession => _state._expansionSession; /// <inheritdoc cref="State.IsFullMethodCallSnippet"/> public bool IsFullMethodCallSnippet => _state.IsFullMethodCallSnippet; public ImmutableArray<ArgumentProvider> GetArgumentProviders(Workspace workspace) { AssertIsForeground(); // TODO: Move this to ArgumentProviderService: https://github.com/dotnet/roslyn/issues/50897 if (_argumentProviders.IsDefault) { _argumentProviders = workspace.Services .SelectMatchingExtensionValues(ExtensionOrderer.Order(_allArgumentProviders), SubjectBuffer.ContentType) .ToImmutableArray(); } return _argumentProviders; } public abstract int GetExpansionFunction(IXMLDOMNode xmlFunctionNode, string bstrFieldName, out IVsExpansionFunction? pFunc); protected abstract ITrackingSpan? InsertEmptyCommentAndGetEndPositionTrackingSpan(); internal abstract Document AddImports(Document document, int position, XElement snippetNode, bool placeSystemNamespaceFirst, bool allowInHiddenRegions, CancellationToken cancellationToken); protected abstract string FallbackDefaultLiteral { get; } public int FormatSpan(IVsTextLines pBuffer, VsTextSpan[] tsInSurfaceBuffer) { AssertIsForeground(); if (ExpansionSession == null) { return VSConstants.E_FAIL; } // If this is a manually-constructed snippet for a full method call, avoid formatting the snippet since // doing so will disrupt signature help. Check ExpansionSession instead of '_state.IsFullMethodCallSnippet' // because '_state._methodNameForInsertFullMethodCall' is not initialized at this point. if (ExpansionSession.TryGetHeaderNode("Description", out var descriptionNode) && descriptionNode?.text == s_fullMethodCallDescriptionSentinel) { return VSConstants.S_OK; } // Formatting a snippet isn't cancellable. var cancellationToken = CancellationToken.None; // At this point, the $selection$ token has been replaced with the selected text and // declarations have been replaced with their default text. We need to format the // inserted snippet text while carefully handling $end$ position (where the caret goes // after Return is pressed). The IVsExpansionSession keeps a tracking point for this // position but we do the tracking ourselves to properly deal with virtual space. To // ensure the end location is correct, we take three extra steps: // 1. Insert an empty comment ("/**/" or "'") at the current $end$ position (prior // to formatting), and keep a tracking span for the comment. // 2. After formatting the new snippet text, find and delete the empty multiline // comment (via the tracking span) and notify the IVsExpansionSession of the new // $end$ location. If the line then contains only whitespace (due to the formatter // putting the empty comment on its own line), then delete the white space and // remember the indentation depth for that line. // 3. When the snippet is finally completed (via Return), and PositionCaretForEditing() // is called, check to see if the end location was on a line containing only white // space in the previous step. If so, and if that line is still empty, then position // the caret in virtual space. // This technique ensures that a snippet like "if($condition$) { $end$ }" will end up // as: // if ($condition$) // { // $end$ // } if (!TryGetSubjectBufferSpan(tsInSurfaceBuffer[0], out var snippetSpan)) { return VSConstants.S_OK; } // Insert empty comment and track end position var snippetTrackingSpan = snippetSpan.CreateTrackingSpan(SpanTrackingMode.EdgeInclusive); var fullSnippetSpan = new VsTextSpan[1]; ExpansionSession.GetSnippetSpan(fullSnippetSpan); var isFullSnippetFormat = fullSnippetSpan[0].iStartLine == tsInSurfaceBuffer[0].iStartLine && fullSnippetSpan[0].iStartIndex == tsInSurfaceBuffer[0].iStartIndex && fullSnippetSpan[0].iEndLine == tsInSurfaceBuffer[0].iEndLine && fullSnippetSpan[0].iEndIndex == tsInSurfaceBuffer[0].iEndIndex; var endPositionTrackingSpan = isFullSnippetFormat ? InsertEmptyCommentAndGetEndPositionTrackingSpan() : null; var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(SubjectBuffer.CurrentSnapshot, snippetTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot)); SubjectBuffer.CurrentSnapshot.FormatAndApplyToBuffer(formattingSpan, CancellationToken.None); if (isFullSnippetFormat) { CleanUpEndLocation(endPositionTrackingSpan); // Unfortunately, this is the only place we can safely add references and imports // specified in the snippet xml. In OnBeforeInsertion we have no guarantee that the // snippet xml will be available, and changing the buffer during OnAfterInsertion can // cause the underlying tracking spans to get out of sync. var currentStartPosition = snippetTrackingSpan.GetStartPoint(SubjectBuffer.CurrentSnapshot).Position; AddReferencesAndImports( ExpansionSession, currentStartPosition, cancellationToken); SetNewEndPosition(endPositionTrackingSpan); } return VSConstants.S_OK; } private void SetNewEndPosition(ITrackingSpan? endTrackingSpan) { RoslynDebug.AssertNotNull(ExpansionSession); if (SetEndPositionIfNoneSpecified(ExpansionSession)) { return; } if (endTrackingSpan != null) { if (!TryGetSpanOnHigherBuffer( endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot), TextView.TextBuffer, out var endSpanInSurfaceBuffer)) { return; } TextView.TextSnapshot.GetLineAndCharacter(endSpanInSurfaceBuffer.Start.Position, out var endLine, out var endChar); ExpansionSession.SetEndSpan(new VsTextSpan { iStartLine = endLine, iStartIndex = endChar, iEndLine = endLine, iEndIndex = endChar }); } } private void CleanUpEndLocation(ITrackingSpan? endTrackingSpan) { if (endTrackingSpan != null) { // Find the empty comment and remove it... var endSnapshotSpan = endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot); SubjectBuffer.Delete(endSnapshotSpan.Span); // Remove the whitespace before the comment if necessary. If whitespace is removed, // then remember the indentation depth so we can appropriately position the caret // in virtual space when the session is ended. var line = SubjectBuffer.CurrentSnapshot.GetLineFromPosition(endSnapshotSpan.Start.Position); var lineText = line.GetText(); if (lineText.Trim() == string.Empty) { _indentCaretOnCommit = true; var document = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var documentOptions = document.GetOptionsAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); _indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, documentOptions.GetOption(FormattingOptions.TabSize)); } else { // If we don't have a document, then just guess the typical default TabSize value. _indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, tabSize: 4); } SubjectBuffer.Delete(new Span(line.Start.Position, line.Length)); _ = SubjectBuffer.CurrentSnapshot.GetSpan(new Span(line.Start.Position, 0)); } } } /// <summary> /// If there was no $end$ token, place it at the end of the snippet code. Otherwise, it /// defaults to the beginning of the snippet code. /// </summary> private static bool SetEndPositionIfNoneSpecified(IVsExpansionSession pSession) { if (!TryGetSnippetNode(pSession, out var snippetNode)) { return false; } var ns = snippetNode.Name.NamespaceName; var codeNode = snippetNode.Element(XName.Get("Code", ns)); if (codeNode == null) { return false; } var delimiterAttribute = codeNode.Attribute("Delimiter"); var delimiter = delimiterAttribute != null ? delimiterAttribute.Value : "$"; if (codeNode.Value.IndexOf(string.Format("{0}end{0}", delimiter), StringComparison.OrdinalIgnoreCase) != -1) { return false; } var snippetSpan = new VsTextSpan[1]; if (pSession.GetSnippetSpan(snippetSpan) != VSConstants.S_OK) { return false; } var newEndSpan = new VsTextSpan { iStartLine = snippetSpan[0].iEndLine, iStartIndex = snippetSpan[0].iEndIndex, iEndLine = snippetSpan[0].iEndLine, iEndIndex = snippetSpan[0].iEndIndex }; pSession.SetEndSpan(newEndSpan); return true; } protected static bool TryGetSnippetNode(IVsExpansionSession pSession, [NotNullWhen(true)] out XElement? snippetNode) { IXMLDOMNode? xmlNode = null; snippetNode = null; try { // Cast to our own version of IVsExpansionSession so that we can get pNode as an // IntPtr instead of a via a RCW. This allows us to guarantee that it pNode is // released before leaving this method. Otherwise, a second invocation of the same // snippet may cause an AccessViolationException. var session = (IVsExpansionSessionInternal)pSession; if (session.GetSnippetNode(null, out var pNode) != VSConstants.S_OK) { return false; } xmlNode = (IXMLDOMNode)Marshal.GetUniqueObjectForIUnknown(pNode); snippetNode = XElement.Parse(xmlNode.xml); return true; } finally { if (xmlNode != null && Marshal.IsComObject(xmlNode)) { Marshal.ReleaseComObject(xmlNode); } } } public int PositionCaretForEditing(IVsTextLines pBuffer, [ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")] VsTextSpan[] ts) { // If the formatted location of the $end$ position (the inserted comment) was on an // empty line and indented, then we have already removed the white space on that line // and the navigation location will be at column 0 on a blank line. We must now // position the caret in virtual space. pBuffer.GetLengthOfLine(ts[0].iStartLine, out var lineLength); pBuffer.GetLineText(ts[0].iStartLine, 0, ts[0].iStartLine, lineLength, out var endLineText); pBuffer.GetPositionOfLine(ts[0].iStartLine, out var endLinePosition); PositionCaretForEditingInternal(endLineText, endLinePosition); return VSConstants.S_OK; } /// <summary> /// Internal for testing purposes. All real caret positioning logic takes place here. <see cref="PositionCaretForEditing"/> /// only extracts the <paramref name="endLineText"/> and <paramref name="endLinePosition"/> from the provided <see cref="IVsTextLines"/>. /// Tests can call this method directly to avoid producing an IVsTextLines. /// </summary> /// <param name="endLineText"></param> /// <param name="endLinePosition"></param> internal void PositionCaretForEditingInternal(string endLineText, int endLinePosition) { if (_indentCaretOnCommit && endLineText == string.Empty) { TextView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(TextView.TextSnapshot.GetPoint(endLinePosition), _indentDepth)); } } public virtual bool TryHandleTab() { if (ExpansionSession != null) { // When 'Tab' is pressed in the last field of a normal snippet, the session wraps back around to the // first field (this is preservation of historical behavior). When 'Tab' is pressed at the end of an // argument provider snippet, the snippet session is automatically committed (this behavior matches the // design for Insert Full Method Call intended for multiple IDEs). var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(fCommitIfLast: _state.IsFullMethodCallSnippet ? 1 : 0); if (!tabbedInsideSnippetField) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); } return tabbedInsideSnippetField; } return false; } public virtual bool TryHandleBackTab() { if (ExpansionSession != null) { var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToPreviousExpansionField(); if (!tabbedInsideSnippetField) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); } return tabbedInsideSnippetField; } return false; } public virtual bool TryHandleEscape() { if (ExpansionSession != null) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); return true; } return false; } public virtual bool TryHandleReturn() { return CommitSnippet(leaveCaret: false); } /// <summary> /// Commit the active snippet, if any. /// </summary> /// <param name="leaveCaret"><see langword="true"/> to leave the caret position unchanged by the call; /// otherwise, <see langword="false"/> to move the caret to the <c>$end$</c> position of the snippet when the /// snippet is committed.</param> /// <returns><see langword="true"/> if the caret may have moved from the call; otherwise, /// <see langword="false"/> if the caret did not move, or if there was no active snippet session to /// commit.</returns> public bool CommitSnippet(bool leaveCaret) { if (ExpansionSession != null) { if (!leaveCaret) { // Only move the caret if the enter was hit within the snippet fields. var hitWithinField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(fCommitIfLast: 0); leaveCaret = !hitWithinField; } ExpansionSession.EndCurrentExpansion(fLeaveCaret: leaveCaret ? 1 : 0); return !leaveCaret; } return false; } public virtual bool TryInsertExpansion(int startPositionInSubjectBuffer, int endPositionInSubjectBuffer, CancellationToken cancellationToken) { var textViewModel = TextView.TextViewModel; if (textViewModel == null) { Debug.Assert(TextView.IsClosed); return false; } // The expansion itself needs to be created in the data buffer, so map everything up var triggerSpan = SubjectBuffer.CurrentSnapshot.GetSpan(startPositionInSubjectBuffer, endPositionInSubjectBuffer - startPositionInSubjectBuffer); if (!TryGetSpanOnHigherBuffer(triggerSpan, textViewModel.DataBuffer, out var dataBufferSpan)) { return false; } var buffer = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer); if (buffer is not IVsExpansion expansion) { return false; } buffer.GetLineIndexOfPosition(dataBufferSpan.Start.Position, out var startLine, out var startIndex); buffer.GetLineIndexOfPosition(dataBufferSpan.End.Position, out var endLine, out var endIndex); var textSpan = new VsTextSpan { iStartLine = startLine, iStartIndex = startIndex, iEndLine = endLine, iEndIndex = endIndex }; if (TryInsertArgumentCompletionSnippet(triggerSpan, dataBufferSpan, expansion, textSpan, cancellationToken)) { Debug.Assert(_state.IsFullMethodCallSnippet); return true; } if (expansion.InsertExpansion(textSpan, textSpan, this, LanguageServiceGuid, out _state._expansionSession) == VSConstants.S_OK) { // This expansion is not derived from a symbol, so make sure the state isn't tracking any symbol // information Debug.Assert(!_state.IsFullMethodCallSnippet); return true; } return false; } private bool TryInsertArgumentCompletionSnippet(SnapshotSpan triggerSpan, SnapshotSpan dataBufferSpan, IVsExpansion expansion, VsTextSpan textSpan, CancellationToken cancellationToken) { if (!(SubjectBuffer.GetFeatureOnOffOption(CompletionOptions.EnableArgumentCompletionSnippets) ?? false)) { // Argument completion snippets are not enabled return false; } var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document is null) { // Couldn't identify the current document return false; } var symbols = ThreadingContext.JoinableTaskFactory.Run(() => GetReferencedSymbolsToLeftOfCaretAsync(document, caretPosition: triggerSpan.End, cancellationToken)); var methodSymbols = symbols.OfType<IMethodSymbol>().ToImmutableArray(); if (methodSymbols.Any()) { // This is the method name as it appears in source text var methodName = dataBufferSpan.GetText(); var snippet = CreateMethodCallSnippet(methodName, includeMethod: true, ImmutableArray<IParameterSymbol>.Empty, ImmutableDictionary<string, string>.Empty); var doc = (DOMDocument)new DOMDocumentClass(); if (doc.loadXML(snippet.ToString(SaveOptions.OmitDuplicateNamespaces))) { if (expansion.InsertSpecificExpansion(doc, textSpan, this, LanguageServiceGuid, pszRelativePath: null, out _state._expansionSession) == VSConstants.S_OK) { Debug.Assert(_state._expansionSession != null); _state._methodNameForInsertFullMethodCall = methodSymbols.First().Name; Debug.Assert(_state._method == null); if (_signatureHelpControllerProvider.GetController(TextView, SubjectBuffer) is { } controller) { EnsureRegisteredForModelUpdatedEvents(this, controller); } // Trigger signature help after starting the snippet session // // TODO: Figure out why ISignatureHelpBroker.TriggerSignatureHelp doesn't work but this does. // https://github.com/dotnet/roslyn/issues/50036 var editorCommandHandlerService = _editorCommandHandlerServiceFactory.GetService(TextView, SubjectBuffer); editorCommandHandlerService.Execute((view, buffer) => new InvokeSignatureHelpCommandArgs(view, buffer), nextCommandHandler: null); return true; } } } return false; // Local function static void EnsureRegisteredForModelUpdatedEvents(AbstractSnippetExpansionClient client, Controller controller) { // Access to _registeredForSignatureHelpEvents is synchronized on the main thread client.ThreadingContext.ThrowIfNotOnUIThread(); if (!client._registeredForSignatureHelpEvents) { client._registeredForSignatureHelpEvents = true; controller.ModelUpdated += client.OnModelUpdated; client.TextView.Closed += delegate { controller.ModelUpdated -= client.OnModelUpdated; }; } } } /// <summary> /// Creates a snippet for providing arguments to a call. /// </summary> /// <param name="methodName">The name of the method as it should appear in code.</param> /// <param name="includeMethod"> /// <para><see langword="true"/> to include the method name and invocation parentheses in the resulting snippet; /// otherwise, <see langword="false"/> if the method name and parentheses are assumed to already exist and the /// template will only specify the argument placeholders. Since the <c>$end$</c> marker is always considered to /// lie after the closing <c>)</c> of the invocation, it is only included when this parameter is /// <see langword="true"/>.</para> /// /// <para>For example, consider a call to <see cref="int.ToString(IFormatProvider)"/>. If /// <paramref name="includeMethod"/> is <see langword="true"/>, the resulting snippet text might look like /// this:</para> /// /// <code> /// ToString($provider$)$end$ /// </code> /// /// <para>If <paramref name="includeMethod"/> is <see langword="false"/>, the resulting snippet text might look /// like this:</para> /// /// <code> /// $provider$ /// </code> /// /// <para>This parameter supports cycling between overloads of a method for argument completion. Since any text /// edit that alters the <c>(</c> or <c>)</c> characters will force the Signature Help session to close, we are /// careful to only update text that lies between these characters.</para> /// </param> /// <param name="parameters">The parameters to the method. If the specific target of the invocation is not /// known, an empty array may be passed to create a template with a placeholder where arguments will eventually /// go.</param> private static XDocument CreateMethodCallSnippet(string methodName, bool includeMethod, ImmutableArray<IParameterSymbol> parameters, ImmutableDictionary<string, string> parameterValues) { XNamespace snippetNamespace = "http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"; var template = new StringBuilder(); if (includeMethod) { template.Append(methodName).Append('('); } var declarations = new List<XElement>(); foreach (var parameter in parameters) { if (declarations.Any()) { template.Append(", "); } // Create a snippet field for the argument. The name of the field matches the parameter name, and the // default value for the field is provided by a call to the internal ArgumentValue snippet function. The // parameter to the snippet function is a serialized SymbolKey which can be mapped back to the // IParameterSymbol. template.Append('$').Append(parameter.Name).Append('$'); declarations.Add(new XElement( snippetNamespace + "Literal", new XElement(snippetNamespace + "ID", new XText(parameter.Name)), new XElement(snippetNamespace + "Default", new XText(parameterValues.GetValueOrDefault(parameter.Name, ""))))); } if (!declarations.Any()) { // If the invocation does not have any parameters, include an empty placeholder in the snippet template // to ensure the caret starts inside the parentheses and can track changes to other overloads (which may // have parameters). template.Append($"${PlaceholderSnippetField}$"); declarations.Add(new XElement( snippetNamespace + "Literal", new XElement(snippetNamespace + "ID", new XText(PlaceholderSnippetField)), new XElement(snippetNamespace + "Default", new XText("")))); } if (includeMethod) { template.Append(')'); } template.Append("$end$"); // A snippet is manually constructed. Replacement fields are added for each argument, and the field name // matches the parameter name. // https://docs.microsoft.com/en-us/visualstudio/ide/code-snippets-schema-reference?view=vs-2019 return new XDocument( new XDeclaration("1.0", "utf-8", null), new XElement( snippetNamespace + "CodeSnippets", new XElement( snippetNamespace + "CodeSnippet", new XAttribute(snippetNamespace + "Format", "1.0.0"), new XElement( snippetNamespace + "Header", new XElement(snippetNamespace + "Title", new XText(methodName)), new XElement(snippetNamespace + "Description", new XText(s_fullMethodCallDescriptionSentinel))), new XElement( snippetNamespace + "Snippet", new XElement(snippetNamespace + "Declarations", declarations.ToArray()), new XElement( snippetNamespace + "Code", new XAttribute(snippetNamespace + "Language", "csharp"), new XCData(template.ToString())))))); } private void OnModelUpdated(object sender, ModelUpdatedEventsArgs e) { AssertIsForeground(); if (e.NewModel is null) { // Signature Help was dismissed, but it's possible for a user to bring it back with Ctrl+Shift+Space. // Leave the snippet session (if any) in its current state to allow it to process either a subsequent // Signature Help update or the Escape/Enter keys that close the snippet session. return; } if (!_state.IsFullMethodCallSnippet) { // Signature Help is showing an updated signature, but either there is no active snippet, or the active // snippet is not performing argument value completion, so we just ignore it. return; } if (!e.NewModel.UserSelected && _state._method is not null) { // This was an implicit signature change which was not triggered by user pressing up/down, and we are // already showing an initialized argument completion snippet session, so avoid switching sessions. return; } var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document is null) { // It's unclear if/how this state would occur, but if it does we would throw an exception trying to // use it. Just return immediately. return; } // TODO: The following blocks the UI thread without cancellation, but it only occurs when an argument value // completion session is active, which is behind an experimental feature flag. // https://github.com/dotnet/roslyn/issues/50634 var compilation = ThreadingContext.JoinableTaskFactory.Run(() => document.Project.GetRequiredCompilationAsync(CancellationToken.None)); var newSymbolKey = (e.NewModel.SelectedItem as AbstractSignatureHelpProvider.SymbolKeySignatureHelpItem)?.SymbolKey ?? default; var newSymbol = newSymbolKey.Resolve(compilation, cancellationToken: CancellationToken.None).GetAnySymbol(); if (newSymbol is not IMethodSymbol method) return; MoveToSpecificMethod(method, CancellationToken.None); } private static async Task<ImmutableArray<ISymbol>> GetReferencedSymbolsToLeftOfCaretAsync( Document document, SnapshotPoint caretPosition, CancellationToken cancellationToken) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var token = await semanticModel.SyntaxTree.GetTouchingWordAsync(caretPosition.Position, document.GetRequiredLanguageService<ISyntaxFactsService>(), cancellationToken).ConfigureAwait(false); if (token.RawKind == 0) { // There is no touching word, so return empty immediately return ImmutableArray<ISymbol>.Empty; } var semanticInfo = semanticModel.GetSemanticInfo(token, document.Project.Solution.Workspace, cancellationToken); return semanticInfo.ReferencedSymbols; } /// <summary> /// Update the current argument value completion session to use a specific method. /// </summary> /// <param name="method">The currently-selected method in Signature Help.</param> /// <param name="cancellationToken">A cancellation token the operation may observe.</param> public void MoveToSpecificMethod(IMethodSymbol method, CancellationToken cancellationToken) { AssertIsForeground(); if (ExpansionSession is null) { return; } if (SymbolEquivalenceComparer.Instance.Equals(_state._method, method)) { return; } if (_state._methodNameForInsertFullMethodCall != method.Name) { // Signature Help is showing a signature that wasn't part of the set this argument value completion // session was created from. It's unclear how this state should be handled, so we stop processing // Signature Help updates for the current session. // TODO: https://github.com/dotnet/roslyn/issues/50636 ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); return; } // If the first method overload chosen is a zero-parameter method, the snippet we'll create is the same snippet // as the one did initially. The editor appears to have a bug where inserting a zero-width snippet (when we update the parameters) // causes the inserted session to immediately dismiss; this works around that issue. if (_state._method is null && method.Parameters.Length == 0) { _state._method = method; return; } var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document is null) { // Couldn't identify the current document ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); return; } var textViewModel = TextView.TextViewModel; if (textViewModel == null) { Debug.Assert(TextView.IsClosed); return; } var buffer = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer); if (buffer is not IVsExpansion expansion) { return; } // We need to replace the portion of the existing Full Method Call snippet which appears inside parentheses. // This span starts at the beginning of the first snippet field, and ends at the end of the last snippet // field. Methods with no arguments still have an empty "placeholder" snippet field representing the initial // caret position when the snippet is created. var textSpan = new VsTextSpan[1]; if (ExpansionSession.GetSnippetSpan(textSpan) != VSConstants.S_OK) { return; } var firstField = _state._method?.Parameters.FirstOrDefault()?.Name ?? PlaceholderSnippetField; if (ExpansionSession.GetFieldSpan(firstField, textSpan) != VSConstants.S_OK) { return; } VsTextSpan adjustedTextSpan; adjustedTextSpan.iStartLine = textSpan[0].iStartLine; adjustedTextSpan.iStartIndex = textSpan[0].iStartIndex; var lastField = _state._method?.Parameters.LastOrDefault()?.Name ?? PlaceholderSnippetField; if (ExpansionSession.GetFieldSpan(lastField, textSpan) != VSConstants.S_OK) { return; } adjustedTextSpan.iEndLine = textSpan[0].iEndLine; adjustedTextSpan.iEndIndex = textSpan[0].iEndIndex; // Track current argument values so input created/updated by a user is not lost when cycling through // Signature Help overloads: // // 1. For each parameter of the method currently presented as a snippet, the value of the argument as // it appears in code. // 2. Place the argument values in a map from parameter name to current value. // 3. (Later) the values in the map can be read to avoid providing new values for equivalent parameters. var newArguments = _state._arguments; if (_state._method is null || !_state._method.Parameters.Any()) { // If we didn't have any previous parameters, then there is only the placeholder in the snippet. // We don't want to lose what the user has typed there, if they typed something if (ExpansionSession.GetFieldValue(PlaceholderSnippetField, out var placeholderValue) == VSConstants.S_OK && placeholderValue.Length > 0) { if (method.Parameters.Any()) { newArguments = newArguments.SetItem(method.Parameters[0].Name, placeholderValue); } else { // TODO: if the user is typing before signature help updated the model, and we have no parameters here, // should we still create a new snippet that has the existing placeholder text? } } } else if (_state._method is not null) { foreach (var previousParameter in _state._method.Parameters) { if (ExpansionSession.GetFieldValue(previousParameter.Name, out var previousValue) == VSConstants.S_OK) { newArguments = newArguments.SetItem(previousParameter.Name, previousValue); } } } // Now compute the new arguments for the new call var semanticModel = document.GetRequiredSemanticModelAsync(cancellationToken).AsTask().WaitAndGetResult(cancellationToken); var position = SubjectBuffer.CurrentSnapshot.GetPosition(adjustedTextSpan.iStartLine, adjustedTextSpan.iStartIndex); foreach (var parameter in method.Parameters) { newArguments.TryGetValue(parameter.Name, out var value); foreach (var provider in GetArgumentProviders(document.Project.Solution.Workspace)) { var context = new ArgumentContext(provider, semanticModel, position, parameter, value, cancellationToken); ThreadingContext.JoinableTaskFactory.Run(() => provider.ProvideArgumentAsync(context)); if (context.DefaultValue is not null) { value = context.DefaultValue; break; } } // If we still have no value, fill in the default if (value is null) { value = FallbackDefaultLiteral; } newArguments = newArguments.SetItem(parameter.Name, value); } var snippet = CreateMethodCallSnippet(method.Name, includeMethod: false, method.Parameters, newArguments); var doc = (DOMDocument)new DOMDocumentClass(); if (doc.loadXML(snippet.ToString(SaveOptions.OmitDuplicateNamespaces))) { if (expansion.InsertSpecificExpansion(doc, adjustedTextSpan, this, LanguageServiceGuid, pszRelativePath: null, out _state._expansionSession) == VSConstants.S_OK) { Debug.Assert(_state._expansionSession != null); _state._methodNameForInsertFullMethodCall = method.Name; _state._method = method; _state._arguments = newArguments; // On this path, the closing parenthesis is not part of the updated snippet, so there is no way for // the snippet itself to represent the $end$ marker (which falls after the ')' character). Instead, // we use the internal APIs to manually specify the effective position of the $end$ marker as the // location in code immediately following the ')'. To do this, we use the knowledge that the snippet // includes all text up to (but not including) the ')', and move that span one position to the // right. if (ExpansionSession.GetEndSpan(textSpan) == VSConstants.S_OK) { textSpan[0].iStartIndex++; textSpan[0].iEndIndex++; ExpansionSession.SetEndSpan(textSpan[0]); } } } } public int EndExpansion() { if (ExpansionSession == null) { _earlyEndExpansionHappened = true; } _state.Clear(); _indentCaretOnCommit = false; return VSConstants.S_OK; } public int IsValidKind(IVsTextLines pBuffer, VsTextSpan[] ts, string bstrKind, out int pfIsValidKind) { pfIsValidKind = 1; return VSConstants.S_OK; } public int IsValidType(IVsTextLines pBuffer, VsTextSpan[] ts, string[] rgTypes, int iCountTypes, out int pfIsValidType) { pfIsValidType = 1; return VSConstants.S_OK; } public int OnAfterInsertion(IVsExpansionSession pSession) { Logger.Log(FunctionId.Snippet_OnAfterInsertion); return VSConstants.S_OK; } public int OnBeforeInsertion(IVsExpansionSession pSession) { Logger.Log(FunctionId.Snippet_OnBeforeInsertion); _state._expansionSession = pSession; // Symbol information (when necessary) is set by the caller return VSConstants.S_OK; } public int OnItemChosen(string pszTitle, string pszPath) { var textViewModel = TextView.TextViewModel; if (textViewModel == null) { Debug.Assert(TextView.IsClosed); return VSConstants.E_FAIL; } int hr; try { VsTextSpan textSpan; GetCaretPositionInSurfaceBuffer(out textSpan.iStartLine, out textSpan.iStartIndex); textSpan.iEndLine = textSpan.iStartLine; textSpan.iEndIndex = textSpan.iStartIndex; var expansion = (IVsExpansion?)EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer); Contract.ThrowIfNull(expansion); _earlyEndExpansionHappened = false; hr = expansion.InsertNamedExpansion(pszTitle, pszPath, textSpan, this, LanguageServiceGuid, fShowDisambiguationUI: 0, pSession: out _state._expansionSession); if (_earlyEndExpansionHappened) { // EndExpansion was called before InsertNamedExpansion returned, so set // expansionSession to null to indicate that there is no active expansion // session. This can occur when the snippet inserted doesn't have any expansion // fields. _state._expansionSession = null; _earlyEndExpansionHappened = false; } } catch (COMException ex) { hr = ex.ErrorCode; } return hr; } private void GetCaretPositionInSurfaceBuffer(out int caretLine, out int caretColumn) { var vsTextView = EditorAdaptersFactoryService.GetViewAdapter(TextView); Contract.ThrowIfNull(vsTextView); vsTextView.GetCaretPos(out caretLine, out caretColumn); vsTextView.GetBuffer(out var textLines); // Handle virtual space (e.g, see Dev10 778675) textLines.GetLengthOfLine(caretLine, out var lineLength); if (caretColumn > lineLength) { caretColumn = lineLength; } } private void AddReferencesAndImports( IVsExpansionSession pSession, int position, CancellationToken cancellationToken) { if (!TryGetSnippetNode(pSession, out var snippetNode)) { return; } var documentWithImports = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (documentWithImports == null) { return; } var documentOptions = documentWithImports.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken); var placeSystemNamespaceFirst = documentOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst); var allowInHiddenRegions = documentWithImports.CanAddImportsInHiddenRegions(); documentWithImports = AddImports(documentWithImports, position, snippetNode, placeSystemNamespaceFirst, allowInHiddenRegions, cancellationToken); AddReferences(documentWithImports.Project, snippetNode); } private void AddReferences(Project originalProject, XElement snippetNode) { var referencesNode = snippetNode.Element(XName.Get("References", snippetNode.Name.NamespaceName)); if (referencesNode == null) { return; } var existingReferenceNames = originalProject.MetadataReferences.Select(r => Path.GetFileNameWithoutExtension(r.Display)); var workspace = originalProject.Solution.Workspace; var projectId = originalProject.Id; var assemblyXmlName = XName.Get("Assembly", snippetNode.Name.NamespaceName); var failedReferenceAdditions = new List<string>(); foreach (var reference in referencesNode.Elements(XName.Get("Reference", snippetNode.Name.NamespaceName))) { // Note: URL references are not supported var assemblyElement = reference.Element(assemblyXmlName); var assemblyName = assemblyElement != null ? assemblyElement.Value.Trim() : null; if (RoslynString.IsNullOrEmpty(assemblyName)) { continue; } if (!(workspace is VisualStudioWorkspaceImpl visualStudioWorkspace) || !visualStudioWorkspace.TryAddReferenceToProject(projectId, assemblyName)) { failedReferenceAdditions.Add(assemblyName); } } if (failedReferenceAdditions.Any()) { var notificationService = workspace.Services.GetRequiredService<INotificationService>(); notificationService.SendNotification( string.Format(ServicesVSResources.The_following_references_were_not_found_0_Please_locate_and_add_them_manually, Environment.NewLine) + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, failedReferenceAdditions), severity: NotificationSeverity.Warning); } } protected static bool TryAddImportsToContainedDocument(Document document, IEnumerable<string> memberImportsNamespaces) { if (!(document.Project.Solution.Workspace is VisualStudioWorkspaceImpl vsWorkspace)) { return false; } var containedDocument = vsWorkspace.TryGetContainedDocument(document.Id); if (containedDocument == null) { return false; } if (containedDocument.ContainedLanguageHost is IVsContainedLanguageHostInternal containedLanguageHost) { foreach (var importClause in memberImportsNamespaces) { if (containedLanguageHost.InsertImportsDirective(importClause) != VSConstants.S_OK) { return false; } } } return true; } protected static bool TryGetSnippetFunctionInfo( IXMLDOMNode xmlFunctionNode, [NotNullWhen(true)] out string? snippetFunctionName, [NotNullWhen(true)] out string? param) { if (xmlFunctionNode.text.IndexOf('(') == -1 || xmlFunctionNode.text.IndexOf(')') == -1 || xmlFunctionNode.text.IndexOf(')') < xmlFunctionNode.text.IndexOf('(')) { snippetFunctionName = null; param = null; return false; } snippetFunctionName = xmlFunctionNode.text.Substring(0, xmlFunctionNode.text.IndexOf('(')); var paramStart = xmlFunctionNode.text.IndexOf('(') + 1; var paramLength = xmlFunctionNode.text.LastIndexOf(')') - xmlFunctionNode.text.IndexOf('(') - 1; param = xmlFunctionNode.text.Substring(paramStart, paramLength); return true; } internal bool TryGetSubjectBufferSpan(VsTextSpan surfaceBufferTextSpan, out SnapshotSpan subjectBufferSpan) { var snapshotSpan = TextView.TextSnapshot.GetSpan(surfaceBufferTextSpan); var subjectBufferSpanCollection = TextView.BufferGraph.MapDownToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, SubjectBuffer); // Bail if a snippet span does not map down to exactly one subject buffer span. if (subjectBufferSpanCollection.Count == 1) { subjectBufferSpan = subjectBufferSpanCollection.Single(); return true; } subjectBufferSpan = default; return false; } internal bool TryGetSpanOnHigherBuffer(SnapshotSpan snapshotSpan, ITextBuffer targetBuffer, out SnapshotSpan span) { var spanCollection = TextView.BufferGraph.MapUpToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, targetBuffer); // Bail if a snippet span does not map up to exactly one span. if (spanCollection.Count == 1) { span = spanCollection.Single(); return true; } span = default; return false; } private sealed class State { /// <summary> /// The current expansion session. /// </summary> public IVsExpansionSession? _expansionSession; /// <summary> /// The symbol name of the method that we have invoked insert full method call on; or <see langword="null"/> /// if there is no active snippet session or the active session is a regular snippets session. /// </summary> public string? _methodNameForInsertFullMethodCall; /// <summary> /// The current symbol presented in an Argument Provider snippet session. This may be null if Signature Help /// has not yet provided a symbol to show. /// </summary> public IMethodSymbol? _method; /// <summary> /// Maps from parameter name to current argument value. When this dictionary does not contain a mapping for /// a parameter, it means no argument has been provided yet by an ArgumentProvider or the user for a /// parameter with this name. This map is cleared at the final end of an argument provider snippet session. /// </summary> public ImmutableDictionary<string, string> _arguments = ImmutableDictionary.Create<string, string>(); /// <summary> /// <see langword="true"/> if the current snippet session is a Full Method Call snippet session; otherwise, /// <see langword="false"/> if there is no current snippet session or if the current snippet session is a normal snippet. /// </summary> public bool IsFullMethodCallSnippet => _expansionSession is not null && _methodNameForInsertFullMethodCall is not null; public void Clear() { _expansionSession = null; _methodNameForInsertFullMethodCall = null; _method = null; _arguments = _arguments.Clear(); } } } }
-1
dotnet/roslyn
55,066
Correctly set IsRetargetable for source assemblies
Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
333fred
2021-07-23T00:55:50Z
2021-07-24T00:08:23Z
a3b5d0f87fbdceadf6d3d1b024aca4736e3e079e
c58fbd573ea1ca0273ef3878782baab73d5201c8
Correctly set IsRetargetable for source assemblies. Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenDeconstructTests.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { [CompilerTrait(CompilerFeature.Tuples)] public class CodeGenDeconstructTests : CSharpTestBase { private static readonly MetadataReference[] s_valueTupleRefs = new[] { SystemRuntimeFacadeRef, ValueTupleRef }; const string commonSource = @"public class Pair<T1, T2> { T1 item1; T2 item2; public Pair(T1 item1, T2 item2) { this.item1 = item1; this.item2 = item2; } public void Deconstruct(out T1 item1, out T2 item2) { System.Console.WriteLine($""Deconstructing {ToString()}""); item1 = this.item1; item2 = this.item2; } public override string ToString() { return $""({item1.ToString()}, {item2.ToString()})""; } } public static class Pair { public static Pair<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Pair<T1, T2>(item1, item2); } } public class Integer { public int state; public override string ToString() { return state.ToString(); } public Integer(int i) { state = i; } public static implicit operator LongInteger(Integer i) { System.Console.WriteLine($""Converting {i}""); return new LongInteger(i.state); } } public class LongInteger { long state; public LongInteger(long l) { state = l; } public override string ToString() { return state.ToString(); } }"; [Fact] public void SimpleAssign() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(x, y)", lhs.ToString()); Assert.Equal("(System.Int64 x, System.String y)", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int64 x, System.String y)", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); var right = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single(); Assert.Equal(@"new C()", right.ToString()); Assert.Equal("C", model.GetTypeInfo(right).Type.ToTestDisplayString()); Assert.Equal("C", model.GetTypeInfo(right).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(right).Kind); }; var comp = CompileAndVerifyWithMscorlib40(source, expectedOutput: "1 hello", references: s_valueTupleRefs, sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 43 (0x2b) .maxstack 3 .locals init (long V_0, //x string V_1, //y int V_2, string V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_2 IL_0007: ldloca.s V_3 IL_0009: callvirt ""void C.Deconstruct(out int, out string)"" IL_000e: ldloc.2 IL_000f: conv.i8 IL_0010: stloc.0 IL_0011: ldloc.3 IL_0012: stloc.1 IL_0013: ldloca.s V_0 IL_0015: call ""string long.ToString()"" IL_001a: ldstr "" "" IL_001f: ldloc.1 IL_0020: call ""string string.Concat(string, string, string)"" IL_0025: call ""void System.Console.WriteLine(string)"" IL_002a: ret }"); } [Fact] public void ObsoleteDeconstructMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); foreach (var (z1, z2) in new[] { new C() }) { } } [System.Obsolete] public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,18): warning CS0612: 'C.Deconstruct(out int, out string)' is obsolete // (x, y) = new C(); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "new C()").WithArguments("C.Deconstruct(out int, out string)").WithLocation(9, 18), // (10,34): warning CS0612: 'C.Deconstruct(out int, out string)' is obsolete // foreach (var (z1, z2) in new[] { new C() }) { } Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "new[] { new C() }").WithArguments("C.Deconstruct(out int, out string)").WithLocation(10, 34) ); } [Fact] [WorkItem(13632, "https://github.com/dotnet/roslyn/issues/13632")] public void SimpleAssignWithoutConversion() { string source = @" class C { static void Main() { int x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 42 (0x2a) .maxstack 3 .locals init (int V_0, //x string V_1, //y int V_2, string V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_2 IL_0007: ldloca.s V_3 IL_0009: callvirt ""void C.Deconstruct(out int, out string)"" IL_000e: ldloc.2 IL_000f: stloc.0 IL_0010: ldloc.3 IL_0011: stloc.1 IL_0012: ldloca.s V_0 IL_0014: call ""string int.ToString()"" IL_0019: ldstr "" "" IL_001e: ldloc.1 IL_001f: call ""string string.Concat(string, string, string)"" IL_0024: call ""void System.Console.WriteLine(string)"" IL_0029: ret }"); } [Fact] public void DeconstructMethodAmbiguous() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } public void Deconstruct(out int a) { a = 2; } }"; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); var deconstruction = (AssignmentExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.SimpleAssignmentExpression).AsNode(); Assert.Equal("(x, y) = new C()", deconstruction.ToString()); var deconstructionInfo = model.GetDeconstructionInfo(deconstruction); var firstDeconstructMethod = ((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("C").GetMembers(WellKnownMemberNames.DeconstructMethodName) .OfType<SourceOrdinaryMethodSymbol>().Where(m => m.ParameterCount == 2).Single(); Assert.Equal(firstDeconstructMethod.GetPublicSymbol(), deconstructionInfo.Method); Assert.Equal("void C.Deconstruct(out System.Int32 a, out System.String b)", deconstructionInfo.Method.ToTestDisplayString()); Assert.Null(deconstructionInfo.Conversion); var nested = deconstructionInfo.Nested; Assert.Equal(2, nested.Length); Assert.Null(nested[0].Method); Assert.Equal(ConversionKind.ImplicitNumeric, nested[0].Conversion.Value.Kind); Assert.Empty(nested[0].Nested); Assert.Null(nested[1].Method); Assert.Equal(ConversionKind.Identity, nested[1].Conversion.Value.Kind); Assert.Empty(nested[1].Nested); var assignment = (AssignmentExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.SimpleAssignmentExpression, occurrence: 2).AsNode(); Assert.Equal("a = 1", assignment.ToString()); var defaultInfo = model.GetDeconstructionInfo(assignment); Assert.Null(defaultInfo.Method); Assert.Empty(defaultInfo.Nested); Assert.Equal(ConversionKind.UnsetConversionKind, defaultInfo.Conversion.Value.Kind); } [Fact] [WorkItem(27520, "https://github.com/dotnet/roslyn/issues/27520")] public void GetDeconstructionInfoOnIncompleteCode() { string source = @" class C { static void M(string s) { foreach (char in s) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS1525: Invalid expression term 'char' // foreach (char in s) { } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "char").WithArguments("char").WithLocation(6, 18), // (6,23): error CS0230: Type and identifier are both required in a foreach statement // foreach (char in s) { } Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(6, 23) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var foreachDeconstruction = (ForEachVariableStatementSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.ForEachVariableStatement).AsNode(); Assert.Equal(@"foreach (char in s) { }", foreachDeconstruction.ToString()); var deconstructionInfo = model.GetDeconstructionInfo(foreachDeconstruction); Assert.Equal(Conversion.UnsetConversion, deconstructionInfo.Conversion); Assert.Null(deconstructionInfo.Method); Assert.Empty(deconstructionInfo.Nested); } [Fact] [WorkItem(15634, "https://github.com/dotnet/roslyn/issues/15634")] public void DeconstructMustReturnVoid() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); } public int Deconstruct(out int a, out string b) { a = 1; b = ""hello""; return 42; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS8129: No Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type. // (x, y) = new C(); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 18) ); } [Fact] public void VerifyExecutionOrder_Deconstruct() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; } static void Main() { C c = new C(); (c.getHolderForX().x, c.getHolderForY().y) = c.getDeconstructReceiver(); } public void Deconstruct(out D1 x, out D2 y) { x = new D1(); y = new D2(); Console.WriteLine(""Deconstruct""); } } class D1 { public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } "; string expected = @"getHolderforX getHolderforY getDeconstructReceiver Deconstruct Conversion1 Conversion2 setX setY "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyExecutionOrder_Deconstruct_Conditional() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; } static void Main() { C c = new C(); bool b = true; (c.getHolderForX().x, c.getHolderForY().y) = b ? c.getDeconstructReceiver() : default; } public void Deconstruct(out D1 x, out D2 y) { x = new D1(); y = new D2(); Console.WriteLine(""Deconstruct""); } } class D1 { public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } "; string expected = @"getHolderforX getHolderforY getDeconstructReceiver Deconstruct Conversion1 Conversion2 setX setY "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyExecutionOrder_TupleLiteral() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } static void Main() { C c = new C(); (c.getHolderForX().x, c.getHolderForY().y) = (new D1(), new D2()); } } class D1 { public D1() { Console.WriteLine(""Constructor1""); } public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public D2() { Console.WriteLine(""Constructor2""); } public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } "; string expected = @"getHolderforX getHolderforY Constructor1 Conversion1 Constructor2 Conversion2 setX setY "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyExecutionOrder_TupleLiteral_Conditional() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } static void Main() { C c = new C(); bool b = true; (c.getHolderForX().x, c.getHolderForY().y) = b ? (new D1(), new D2()) : default; } } class D1 { public D1() { Console.WriteLine(""Constructor1""); } public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public D2() { Console.WriteLine(""Constructor2""); } public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } "; string expected = @"getHolderforX getHolderforY Constructor1 Constructor2 Conversion1 Conversion2 setX setY "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyExecutionOrder_TupleLiteralAndDeconstruction() { string source = @" using System; class C { int w { set { Console.WriteLine($""setW""); } } int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } int z { set { Console.WriteLine($""setZ""); } } C getHolderForW() { Console.WriteLine(""getHolderforW""); return this; } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; } static void Main() { C c = new C(); (c.getHolderForW().w, (c.getHolderForY().y, c.getHolderForZ().z), c.getHolderForX().x) = (new D1(), new D2(), new D3()); } } class D1 { public D1() { Console.WriteLine(""Constructor1""); } public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public D2() { Console.WriteLine(""Constructor2""); } public void Deconstruct(out int x, out int y) { x = 2; y = 3; Console.WriteLine(""deconstruct""); } } class D3 { public D3() { Console.WriteLine(""Constructor3""); } public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; } } "; string expected = @"getHolderforW getHolderforY getHolderforZ getHolderforX Constructor1 Conversion1 Constructor2 Constructor3 Conversion3 deconstruct setW setY setZ setX "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyExecutionOrder_TupleLiteralAndDeconstruction_Conditional() { string source = @" using System; class C { int w { set { Console.WriteLine($""setW""); } } int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } int z { set { Console.WriteLine($""setZ""); } } C getHolderForW() { Console.WriteLine(""getHolderforW""); return this; } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; } static void Main() { C c = new C(); bool b = false; (c.getHolderForW().w, (c.getHolderForY().y, c.getHolderForZ().z), c.getHolderForX().x) = b ? default : (new D1(), new D2(), new D3()); } } class D1 { public D1() { Console.WriteLine(""Constructor1""); } public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public D2() { Console.WriteLine(""Constructor2""); } public void Deconstruct(out int x, out int y) { x = 2; y = 3; Console.WriteLine(""deconstruct""); } } class D3 { public D3() { Console.WriteLine(""Constructor3""); } public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; } } "; string expected = @"getHolderforW getHolderforY getHolderforZ getHolderforX Constructor1 Constructor2 Constructor3 deconstruct Conversion1 Conversion3 setW setY setZ setX "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void DifferentVariableKinds() { string source = @" class C { int[] ArrayIndexer = new int[1]; string property; string Property { set { property = value; } } string AutoProperty { get; set; } static void Main() { C c = new C(); (c.ArrayIndexer[0], c.Property, c.AutoProperty) = new C(); System.Console.WriteLine(c.ArrayIndexer[0] + "" "" + c.property + "" "" + c.AutoProperty); } public void Deconstruct(out int a, out string b, out string c) { a = 1; b = ""hello""; c = ""world""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello world"); comp.VerifyDiagnostics(); } [Fact] public void Dynamic() { string source = @" class C { dynamic Dynamic1; dynamic Dynamic2; static void Main() { C c = new C(); (c.Dynamic1, c.Dynamic2) = c; System.Console.WriteLine(c.Dynamic1 + "" "" + c.Dynamic2); } public void Deconstruct(out int a, out dynamic b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DeconstructInterfaceOnStruct() { string source = @" interface IDeconstructable { void Deconstruct(out int a, out string b); } struct C : IDeconstructable { string state; static void Main() { int x; string y; IDeconstructable c = new C() { state = ""initial"" }; System.Console.Write(c); (x, y) = c; System.Console.WriteLine("" "" + c + "" "" + x + "" "" + y); } void IDeconstructable.Deconstruct(out int a, out string b) { a = 1; b = ""hello""; state = ""modified""; } public override string ToString() { return state; } } "; var comp = CompileAndVerify(source, expectedOutput: "initial modified 1 hello", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DeconstructMethodHasParams2() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b, params int[] c) // not a Deconstruct operator { a = 1; b = ""ignored""; } public void Deconstruct(out int a, out string b) { a = 2; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "2 hello"); comp.VerifyDiagnostics(); } [Fact] public void OutParamsDisallowed() { string source = @" class C { public void Deconstruct(out int a, out string b, out params int[] c) { a = 1; b = ""ignored""; c = new[] { 2, 2 }; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,58): error CS8328: The parameter modifier 'params' cannot be used with 'out' // public void Deconstruct(out int a, out string b, out params int[] c) Diagnostic(ErrorCode.ERR_BadParameterModifiers, "params").WithArguments("params", "out").WithLocation(4, 58)); } [Fact] public void DeconstructMethodHasArglist2() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } public void Deconstruct(out int a, out string b, __arglist) // not a Deconstruct operator { a = 2; b = ""ignored""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DifferentStaticVariableKinds() { string source = @" class C { static int[] ArrayIndexer = new int[1]; static string property; static string Property { set { property = value; } } static string AutoProperty { get; set; } static void Main() { (C.ArrayIndexer[0], C.Property, C.AutoProperty) = new C(); System.Console.WriteLine(C.ArrayIndexer[0] + "" "" + C.property + "" "" + C.AutoProperty); } public void Deconstruct(out int a, out string b, out string c) { a = 1; b = ""hello""; c = ""world""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello world"); comp.VerifyDiagnostics(); } [Fact] public void DifferentVariableRefKinds() { string source = @" class C { static void Main() { long a = 1; int b; C.M(ref a, out b); System.Console.WriteLine(a + "" "" + b); } static void M(ref long a, out int b) { (a, b) = new C(); } public void Deconstruct(out int x, out byte y) { x = 2; y = (byte)3; } } "; var comp = CompileAndVerify(source, expectedOutput: "2 3"); comp.VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.RefLocalsReturns)] public void RefReturningMethod() { string source = @" class C { static int i = 0; static void Main() { (M(), M()) = new C(); System.Console.WriteLine($""Final i is {i}""); } static ref int M() { System.Console.WriteLine($""M (previous i is {i})""); return ref i; } void Deconstruct(out int x, out int y) { System.Console.WriteLine(""Deconstruct""); x = 42; y = 43; } } "; var expected = @"M (previous i is 0) M (previous i is 0) Deconstruct Final i is 43 "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact, CompilerTrait(CompilerFeature.RefLocalsReturns)] public void RefReturningProperty() { string source = @" class C { static int i = 0; static void Main() { (P, P) = new C(); System.Console.WriteLine($""Final i is {i}""); } static ref int P { get { System.Console.WriteLine($""P (previous i is {i})""); return ref i; } } void Deconstruct(out int x, out int y) { System.Console.WriteLine(""Deconstruct""); x = 42; y = 43; } } "; var expected = @"P (previous i is 0) P (previous i is 0) Deconstruct Final i is 43 "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.RefLocalsReturns)] public void RefReturningMethodFlow() { string source = @" struct C { static C i; static C P { get { System.Console.WriteLine(""getP""); return i; } set { System.Console.WriteLine(""setP""); i = value; } } static void Main() { (M(), M()) = P; } static ref C M() { System.Console.WriteLine($""M (previous i is {i})""); return ref i; } void Deconstruct(out int x, out int y) { System.Console.WriteLine(""Deconstruct""); x = 42; y = 43; } public static implicit operator C(int x) { System.Console.WriteLine(""conversion""); return new C(); } } "; var expected = @"M (previous i is C) M (previous i is C) getP Deconstruct conversion conversion"; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void Indexers() { string source = @" class C { static SomeArray array; static void Main() { int y; (Goo()[Bar()], y) = new C(); System.Console.WriteLine($""Final array values[2] {array.values[2]}""); } static SomeArray Goo() { System.Console.WriteLine($""Goo""); array = new SomeArray(); return array; } static int Bar() { System.Console.WriteLine($""Bar""); return 2; } void Deconstruct(out int x, out int y) { System.Console.WriteLine(""Deconstruct""); x = 101; y = 102; } } class SomeArray { public int[] values; public SomeArray() { values = new [] { 42, 43, 44 }; } public int this[int index] { get { System.Console.WriteLine($""indexGet (with value {values[index]})""); return values[index]; } set { System.Console.WriteLine($""indexSet (with value {value})""); values[index] = value; } } } "; var expected = @"Goo Bar Deconstruct indexSet (with value 101) Final array values[2] 101 "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void AssigningTuple() { string source = @" class C { static void Main() { long x; string y; int i = 1; (x, y) = (i, ""hello""); System.Console.WriteLine(x + "" "" + y); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); var deconstruction = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Single(); var deconstructionInfo = model.GetDeconstructionInfo(deconstruction); Assert.Null(deconstructionInfo.Method); Assert.Null(deconstructionInfo.Conversion); var nested = deconstructionInfo.Nested; Assert.Equal(2, nested.Length); Assert.Null(nested[0].Method); Assert.Equal(ConversionKind.Identity, nested[0].Conversion.Value.Kind); Assert.Empty(nested[0].Nested); Assert.Null(nested[1].Method); Assert.Equal(ConversionKind.Identity, nested[1].Conversion.Value.Kind); Assert.Empty(nested[1].Nested); var tuple = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(i, ""hello"")", tuple.ToString()); var tupleConversion = model.GetConversion(tuple); Assert.Equal(ConversionKind.ImplicitTupleLiteral, tupleConversion.Kind); Assert.Equal(ConversionKind.ImplicitNumeric, tupleConversion.UnderlyingConversions[0].Kind); } [Fact] public void AssigningTupleWithConversion() { string source = @" class C { static void Main() { long x; string y; (x, y) = M(); System.Console.WriteLine(x + "" "" + y); } static System.ValueTuple<int, string> M() { return (1, ""hello""); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); } [Fact] public void AssigningLongTuple() { string source = @" class C { static void Main() { long x; int y; (x, x, x, x, x, x, x, x, x, y) = (1, 1, 1, 1, 1, 1, 1, 1, 4, 2); System.Console.WriteLine(string.Concat(x, "" "", y)); } } "; var comp = CompileAndVerify(source, expectedOutput: "4 2"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0) //y IL_0000: ldc.i4.4 IL_0001: conv.i8 IL_0002: ldc.i4.2 IL_0003: stloc.0 IL_0004: box ""long"" IL_0009: ldstr "" "" IL_000e: ldloc.0 IL_000f: box ""int"" IL_0014: call ""string string.Concat(object, object, object)"" IL_0019: call ""void System.Console.WriteLine(string)"" IL_001e: ret }"); } [Fact] public void AssigningLongTupleWithNames() { string source = @" class C { static void Main() { long x; int y; (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); System.Console.WriteLine(x + "" "" + y); } } "; var comp = CompileAndVerify(source, expectedOutput: "9 10"); comp.VerifyDiagnostics( // (9,43): warning CS8123: The tuple element name 'a' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "a: 1").WithArguments("a", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 43), // (9,49): warning CS8123: The tuple element name 'b' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: 2").WithArguments("b", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 49), // (9,55): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 3").WithArguments("c", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 55), // (9,61): warning CS8123: The tuple element name 'd' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "d: 4").WithArguments("d", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 61), // (9,67): warning CS8123: The tuple element name 'e' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "e: 5").WithArguments("e", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 67), // (9,73): warning CS8123: The tuple element name 'f' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "f: 6").WithArguments("f", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 73), // (9,79): warning CS8123: The tuple element name 'g' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "g: 7").WithArguments("g", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 79), // (9,85): warning CS8123: The tuple element name 'h' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "h: 8").WithArguments("h", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 85), // (9,91): warning CS8123: The tuple element name 'i' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "i: 9").WithArguments("i", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 91), // (9,97): warning CS8123: The tuple element name 'j' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "j: 10").WithArguments("j", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 97) ); } [Fact] public void AssigningLongTuple2() { string source = @" class C { static void Main() { long x; int y; (x, x, x, x, x, x, x, x, x, y) = (1, 1, 1, 1, 1, 1, 1, 1, 4, (byte)2); System.Console.WriteLine(x + "" "" + y); } } "; var comp = CompileAndVerify(source, expectedOutput: "4 2"); comp.VerifyDiagnostics(); } [Fact] public void AssigningTypelessTuple() { string source = @" class C { static void Main() { string x = ""goodbye""; string y; (x, y) = (null, ""hello""); System.Console.WriteLine($""{x}{y}""); } } "; var comp = CompileAndVerify(source, expectedOutput: "hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 19 (0x13) .maxstack 2 .locals init (string V_0) //y IL_0000: ldnull IL_0001: ldstr ""hello"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""string string.Concat(string, string)"" IL_000d: call ""void System.Console.WriteLine(string)"" IL_0012: ret } "); } [Fact] public void ValueTupleReturnIsNotEmittedIfUnused() { string source = @" class C { public static void Main() { int x, y; (x, y) = new C(); } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 15 (0xf) .maxstack 3 .locals init (int V_0, int V_1) IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_0 IL_0007: ldloca.s V_1 IL_0009: callvirt ""void C.Deconstruct(out int, out int)"" IL_000e: ret }"); } [Fact] public void ValueTupleReturnIsEmittedIfUsed() { string source = @" class C { public static void Main() { int x, y; var z = ((x, y) = new C()); z.ToString(); } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x = nodes.OfType<VariableDeclaratorSyntax>().ElementAt(2); Assert.Equal("(System.Int32 x, System.Int32 y) z", model.GetDeclaredSymbol(x).ToTestDisplayString()); }; var comp = CompileAndVerify(source, sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 37 (0x25) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0, //z int V_1, int V_2) IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_1 IL_0007: ldloca.s V_2 IL_0009: callvirt ""void C.Deconstruct(out int, out int)"" IL_000e: ldloc.1 IL_000f: ldloc.2 IL_0010: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0015: stloc.0 IL_0016: ldloca.s V_0 IL_0018: constrained. ""System.ValueTuple<int, int>"" IL_001e: callvirt ""string object.ToString()"" IL_0023: pop IL_0024: ret }"); } [Fact] public void ValueTupleReturnIsEmittedIfUsed_WithCSharp7_1() { string source = @" class C { public static void Main() { int x, y; var z = ((x, y) = new C()); z.ToString(); } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x = nodes.OfType<VariableDeclaratorSyntax>().ElementAt(2); Assert.Equal("(System.Int32 x, System.Int32 y) z", model.GetDeclaredSymbol(x).ToTestDisplayString()); }; var comp = CompileAndVerify(source, sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics(); } [Fact] [WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")] public void ValueTupleNotRequiredIfReturnIsNotUsed() { string source = @" class C { public static void Main() { int x, y; (x, y) = new C(); System.Console.Write($""assignment: {x} {y}. ""); foreach (var (a, b) in new[] { new C() }) { System.Console.Write($""foreach: {a} {b}.""); } } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Regular7, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "assignment: 1 2. foreach: 1 2."); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var xy = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal("(x, y)", xy.ToString()); var tuple1 = model.GetTypeInfo(xy).Type; Assert.Equal("(System.Int32 x, System.Int32 y)[missing]", tuple1.ToTestDisplayString()); var ab = nodes.OfType<DeclarationExpressionSyntax>().Single(); var tuple2 = model.GetTypeInfo(ab).Type; Assert.Equal("(System.Int32 a, System.Int32 b)[missing]", tuple2.ToTestDisplayString()); Assert.Equal("(System.Int32 a, System.Int32 b)[missing]", model.GetTypeInfo(ab).ConvertedType.ToTestDisplayString()); } [Fact] [WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")] public void ValueTupleNotRequiredIfReturnIsNotUsed2() { string source = @" class C { public static void Main() { int x, y; for((x, y) = new C(1); ; (x, y) = new C(2)) { } } public C(int c) { } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Regular7, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var tuple1 = nodes.OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(x, y) = new C(1)", tuple1.Parent.ToString()); var tupleType1 = model.GetTypeInfo(tuple1).Type; Assert.Equal("(System.Int32 x, System.Int32 y)[missing]", tupleType1.ToTestDisplayString()); var tuple2 = nodes.OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(x, y) = new C(2)", tuple2.Parent.ToString()); var tupleType2 = model.GetTypeInfo(tuple1).Type; Assert.Equal("(System.Int32 x, System.Int32 y)[missing]", tupleType2.ToTestDisplayString()); } [Fact] [WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")] public void ValueTupleNotRequiredIfReturnIsNotUsed3() { string source = @" class C { public static void Main() { int x, y; (x, y) = new C(); } public C() { } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } namespace System { [Obsolete] public struct ValueTuple<T1, T2> { [Obsolete] public T1 Item1; [Obsolete] public T2 Item2; public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyEmitDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var tuple = nodes.OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(x, y) = new C()", tuple.Parent.ToString()); var tupleType = model.GetTypeInfo(tuple).Type; Assert.Equal("(System.Int32 x, System.Int32 y)", tupleType.ToTestDisplayString()); var underlying = ((INamedTypeSymbol)tupleType).TupleUnderlyingType; Assert.Equal("(System.Int32, System.Int32)", underlying.ToTestDisplayString()); } [Fact] [WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")] public void ValueTupleRequiredWhenRightHandSideIsTuple() { string source = @" class C { public static void Main() { int x, y; (x, y) = (1, 2); } } "; var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (7,18): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(1, 2)").WithArguments("System.ValueTuple`2").WithLocation(7, 18) ); } [Fact] [WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")] public void ValueTupleRequiredWhenRightHandSideIsTupleButNoReferenceEmitted() { string source = @" class C { public static void Main() { int x, y; (x, y) = (1, 2); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); Action<PEAssembly> assemblyValidator = assembly => { var reader = assembly.GetMetadataReader(); var names = reader.GetAssemblyRefNames().Select(name => reader.GetString(name)); Assert.Empty(names.Where(name => name.Contains("ValueTuple"))); }; CompileAndVerifyCommon(comp, assemblyValidator: assemblyValidator); } [Fact] public void ValueTupleReturnMissingMemberWithCSharp7() { string source = @" class C { public void M() { int x, y; var nested = ((x, y) = (1, 2)); System.Console.Write(nested.x); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyDiagnostics( // (8,37): error CS8305: Tuple element name 'x' is inferred. Please use language version 7.1 or greater to access an element by its inferred name. // System.Console.Write(nested.x); Diagnostic(ErrorCode.ERR_TupleInferredNamesNotAvailable, "x").WithArguments("x", "7.1").WithLocation(8, 37) ); } [Fact] public void ValueTupleReturnWithInferredNamesWithCSharp7_1() { string source = @" class C { public void M() { int x, y, Item1, Rest; var a = ((x, y) = (1, 2)); var b = ((x, x) = (1, 2)); var c = ((_, x) = (1, 2)); var d = ((Item1, Rest) = (1, 2)); var nested = ((x, Item1, y, (_, x, x), (x, y)) = (1, 2, 3, (4, 5, 6), (7, 8))); (int, int) f = ((x, y) = (1, 2)); } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var declarations = nodes.OfType<VariableDeclaratorSyntax>(); Assert.Equal("(System.Int32 x, System.Int32 y) a", model.GetDeclaredSymbol(declarations.ElementAt(4)).ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32) b", model.GetDeclaredSymbol(declarations.ElementAt(5)).ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32 x) c", model.GetDeclaredSymbol(declarations.ElementAt(6)).ToTestDisplayString()); var x = (ILocalSymbol)model.GetDeclaredSymbol(declarations.ElementAt(7)); Assert.Equal("(System.Int32, System.Int32) d", x.ToTestDisplayString()); Assert.True(x.Type.GetSymbol().TupleElementNames.IsDefault); Assert.Equal("(System.Int32 x, System.Int32, System.Int32 y, (System.Int32, System.Int32, System.Int32), (System.Int32 x, System.Int32 y)) nested", model.GetDeclaredSymbol(declarations.ElementAt(8)).ToTestDisplayString()); }; var comp = CompileAndVerify(source, sourceSymbolValidator: validator, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyDiagnostics(); } [Fact] public void DeconstructionDeclarationCanOnlyBeParsedAsStatement() { string source = @" class C { public static void Main() { var z = ((var x, int y) = new C()); } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,19): error CS8185: A declaration is not allowed in this context. // var z = ((var x, int y) = new C()); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x").WithLocation(6, 19) ); } [ConditionalFact(typeof(DesktopOnly))] public void Constraints_01() { string source = @" using System; class C { public void M() { (int x, var (err1, y)) = (0, new C()); // ok, no return value used (ArgIterator err2, var err3) = M2(); // ok, no return value foreach ((ArgIterator err4, var err5) in new[] { M2() }) // ok, no return value { } } public static (ArgIterator, ArgIterator) M2() { return (default(ArgIterator), default(ArgIterator)); } public void Deconstruct(out ArgIterator a, out int b) { a = default(ArgIterator); b = 2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (19,29): error CS1601: Cannot make reference to variable of type 'ArgIterator' // public void Deconstruct(out ArgIterator a, out int b) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out ArgIterator a").WithArguments("System.ArgIterator").WithLocation(19, 29), // (14,46): error CS0306: The type 'ArgIterator' may not be used as a type argument // public static (ArgIterator, ArgIterator) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("System.ArgIterator").WithLocation(14, 46), // (14,46): error CS0306: The type 'ArgIterator' may not be used as a type argument // public static (ArgIterator, ArgIterator) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("System.ArgIterator").WithLocation(14, 46), // (16,17): error CS0306: The type 'ArgIterator' may not be used as a type argument // return (default(ArgIterator), default(ArgIterator)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(ArgIterator)").WithArguments("System.ArgIterator").WithLocation(16, 17), // (16,39): error CS0306: The type 'ArgIterator' may not be used as a type argument // return (default(ArgIterator), default(ArgIterator)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(ArgIterator)").WithArguments("System.ArgIterator").WithLocation(16, 39) ); } [Fact] public void Constraints_02() { string source = @" unsafe class C { public void M() { (int x, var (err1, y)) = (0, new C()); // ok, no return value (var err2, var err3) = M2(); // ok, no return value foreach ((var err4, var err5) in new[] { M2() }) // ok, no return value { } } public static (int*, int*) M2() { return (default(int*), default(int*)); } public void Deconstruct(out int* a, out int b) { a = default(int*); b = 2; } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (13,32): error CS0306: The type 'int*' may not be used as a type argument // public static (int*, int*) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(13, 32), // (13,32): error CS0306: The type 'int*' may not be used as a type argument // public static (int*, int*) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(13, 32), // (15,17): error CS0306: The type 'int*' may not be used as a type argument // return (default(int*), default(int*)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(int*)").WithArguments("int*").WithLocation(15, 17), // (15,32): error CS0306: The type 'int*' may not be used as a type argument // return (default(int*), default(int*)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(int*)").WithArguments("int*").WithLocation(15, 32) ); } [Fact] public void Constraints_03() { string source = @" unsafe class C { public void M() { int ok; int* err1, err2; var t = ((ok, (err1, ok)) = (0, new C())); var t2 = ((err1, err2) = M2()); } public static (int*, int*) M2() { throw null; } public void Deconstruct(out int* a, out int b) { a = default(int*); b = 2; } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (12,32): error CS0306: The type 'int*' may not be used as a type argument // public static (int*, int*) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(12, 32), // (12,32): error CS0306: The type 'int*' may not be used as a type argument // public static (int*, int*) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(12, 32), // (8,24): error CS0306: The type 'int*' may not be used as a type argument // var t = ((ok, (err1, ok)) = (0, new C())); Diagnostic(ErrorCode.ERR_BadTypeArgument, "err1").WithArguments("int*").WithLocation(8, 24), // (9,20): error CS0306: The type 'int*' may not be used as a type argument // var t2 = ((err1, err2) = M2()); Diagnostic(ErrorCode.ERR_BadTypeArgument, "err1").WithArguments("int*").WithLocation(9, 20), // (9,26): error CS0306: The type 'int*' may not be used as a type argument // var t2 = ((err1, err2) = M2()); Diagnostic(ErrorCode.ERR_BadTypeArgument, "err2").WithArguments("int*").WithLocation(9, 26) ); } [Fact] public void DeconstructionWithTupleNamesCannotBeParsed() { string source = @" class C { public static void Main() { (Alice: var x, Bob: int y) = (1, 2); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,10): error CS8187: Tuple element names are not permitted on the left of a deconstruction. // (Alice: var x, Bob: int y) = (1, 2); Diagnostic(ErrorCode.ERR_TupleElementNamesInDeconstruction, "Alice:").WithLocation(6, 10), // (6,24): error CS8187: Tuple element names are not permitted on the left of a deconstruction. // (Alice: var x, Bob: int y) = (1, 2); Diagnostic(ErrorCode.ERR_TupleElementNamesInDeconstruction, "Bob:").WithLocation(6, 24) ); } [Fact] public void ValueTupleReturnIsEmittedIfUsedInLambda() { string source = @" class C { static void F(System.Action a) { } static void F<T>(System.Func<T> f) { System.Console.Write(f().ToString()); } static void Main() { int x, y; F(() => (x, y) = (1, 2)); } } "; var comp = CompileAndVerify(source, expectedOutput: "(1, 2)"); comp.VerifyDiagnostics(); } [Fact] public void AssigningIntoProperties() { string source = @" class C { static int field; static long x { set { System.Console.WriteLine($""setX {value}""); } } static string y { get; set; } static ref int z { get { return ref field; } } static void Main() { (x, y, z) = new C(); System.Console.WriteLine(y); System.Console.WriteLine($""field: {field}""); } public void Deconstruct(out int a, out string b, out int c) { a = 1; b = ""hello""; c = 2; } } "; string expected = @"setX 1 hello field: 2 "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void AssigningTupleIntoProperties() { string source = @" class C { static int field; static long x { set { System.Console.WriteLine($""setX {value}""); } } static string y { get; set; } static ref int z { get { return ref field; } } static void Main() { (x, y, z) = (1, ""hello"", 2); System.Console.WriteLine(y); System.Console.WriteLine($""field: {field}""); } } "; string expected = @"setX 1 hello field: 2 "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] [WorkItem(18554, "https://github.com/dotnet/roslyn/issues/18554")] public void AssigningIntoIndexers() { string source = @" using System; class C { int field; ref int this[int x, int y, int z, int opt = 1] { get { Console.WriteLine($""this.get""); return ref field; } } int this[int x, long y, int z, int opt = 1] { set { Console.WriteLine($""this.set({value})""); } } int M(int i) { Console.WriteLine($""M({i})""); return 0; } void Test() { (this[z: M(1), x: M(2), y: 10], this[z: M(3), x: M(4), y: 10L]) = this; Console.WriteLine($""field: {field}""); } static void Main() { new C().Test(); } void Deconstruct(out int a, out int b) { Console.WriteLine(nameof(Deconstruct)); a = 1; b = 2; } } "; var expectedOutput = @"M(1) M(2) this.get M(3) M(4) Deconstruct this.set(2) field: 1 "; var comp = CompileAndVerify(source, expectedOutput: expectedOutput); comp.VerifyDiagnostics(); } [Fact] [WorkItem(18554, "https://github.com/dotnet/roslyn/issues/18554")] public void AssigningTupleIntoIndexers() { string source = @" using System; class C { int field; ref int this[int x, int y, int z, int opt = 1] { get { Console.WriteLine($""this.get""); return ref field; } } int this[int x, long y, int z, int opt = 1] { set { Console.WriteLine($""this.set({value})""); } } int M(int i) { Console.WriteLine($""M({i})""); return 0; } void Test() { (this[z: M(1), x: M(2), y: 10], this[z: M(3), x: M(4), y: 10L]) = (1, 2); Console.WriteLine($""field: {field}""); } static void Main() { new C().Test(); } } "; var expectedOutput = @"M(1) M(2) this.get M(3) M(4) this.set(2) field: 1 "; var comp = CompileAndVerify(source, expectedOutput: expectedOutput); comp.VerifyDiagnostics(); } [Fact] public void AssigningIntoIndexerWithOptionalValueParameter() { var ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6d 00 00 ) .method public hidebysig specialname instance void set_Item ( int32 i, [opt] int32 'value' ) cil managed { .param [2] = int32(1) .maxstack 8 IL_0000: ldstr ""this.set({0})"" IL_0005: ldarg.2 IL_0006: box[mscorlib]System.Int32 IL_000b: call string[mscorlib] System.String::Format(string, object) IL_0010: call void [mscorlib]System.Console::WriteLine(string) IL_0015: ret } // end of method C::set_Item .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor .property instance int32 Item( int32 i ) { .set instance void C::set_Item(int32, int32) } } // end of class C "; var source = @" class Program { static void Main() { var c = new C(); (c[1], c[2]) = (1, 2); } } "; string expectedOutput = @"this.set(1) this.set(2) "; var comp = CreateCompilationWithILAndMscorlib40(source, ilSource, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: expectedOutput).VerifyDiagnostics(); } [Fact] public void Swap() { string source = @" class C { static int x = 2; static int y = 4; static void Main() { Swap(); System.Console.WriteLine(x + "" "" + y); } static void Swap() { (x, y) = (y, x); } } "; var comp = CompileAndVerify(source, expectedOutput: "4 2"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Swap", @" { // Code size 23 (0x17) .maxstack 2 .locals init (int V_0) IL_0000: ldsfld ""int C.y"" IL_0005: ldsfld ""int C.x"" IL_000a: stloc.0 IL_000b: stsfld ""int C.x"" IL_0010: ldloc.0 IL_0011: stsfld ""int C.y"" IL_0016: ret } "); } [Fact] public void CircularFlow() { string source = @" class C { static void Main() { (object i, object ii) x = (1, 2); object y; (x.ii, y) = x; System.Console.WriteLine(x + "" "" + y); } } "; var comp = CompileAndVerify(source, expectedOutput: "(1, 1) 2"); comp.VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.RefLocalsReturns)] public void CircularFlow2() { string source = @" class C { static void Main() { (object i, object ii) x = (1,2); object y; ref var a = ref x; (a.ii, y) = x; System.Console.WriteLine(x + "" "" + y); } } "; var comp = CompileAndVerify(source, expectedOutput: "(1, 1) 2", parseOptions: TestOptions.Regular.WithRefsFeature()); comp.VerifyDiagnostics(); } [Fact] public void DeconstructUsingBaseDeconstructMethod() { string source = @" class Base { public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } class C : Base { static void Main() { int x, y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int c) { c = 42; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2", parseOptions: TestOptions.Regular.WithRefsFeature()); comp.VerifyDiagnostics(); } [Fact] public void NestedDeconstructUsingSystemTupleExtensionMethod() { string source = @" using System; class C { static void Main() { int x; string y, z; (x, (y, z)) = Tuple.Create(1, Tuple.Create(""hello"", ""world"")); System.Console.WriteLine(x + "" "" + y + "" "" + z); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello world", parseOptions: TestOptions.Regular.WithRefsFeature()); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); var deconstruction = (AssignmentExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.SimpleAssignmentExpression).AsNode(); Assert.Equal(@"(x, (y, z)) = Tuple.Create(1, Tuple.Create(""hello"", ""world""))", deconstruction.ToString()); var deconstructionInfo = model.GetDeconstructionInfo(deconstruction); Assert.Equal("void System.TupleExtensions.Deconstruct<System.Int32, System.Tuple<System.String, System.String>>(" + "this System.Tuple<System.Int32, System.Tuple<System.String, System.String>> value, " + "out System.Int32 item1, out System.Tuple<System.String, System.String> item2)", deconstructionInfo.Method.ToTestDisplayString()); Assert.Null(deconstructionInfo.Conversion); var nested = deconstructionInfo.Nested; Assert.Equal(2, nested.Length); Assert.Null(nested[0].Method); Assert.Equal(ConversionKind.Identity, nested[0].Conversion.Value.Kind); Assert.Empty(nested[0].Nested); Assert.Equal("void System.TupleExtensions.Deconstruct<System.String, System.String>(" + "this System.Tuple<System.String, System.String> value, " + "out System.String item1, out System.String item2)", nested[1].Method.ToTestDisplayString()); Assert.Null(nested[1].Conversion); var nested2 = nested[1].Nested; Assert.Equal(2, nested.Length); Assert.Null(nested2[0].Method); Assert.Equal(ConversionKind.Identity, nested2[0].Conversion.Value.Kind); Assert.Empty(nested2[0].Nested); Assert.Null(nested2[1].Method); Assert.Equal(ConversionKind.Identity, nested2[1].Conversion.Value.Kind); Assert.Empty(nested2[1].Nested); } [Fact] public void DeconstructUsingValueTupleExtensionMethod() { string source = @" class C { static void Main() { int x; string y, z; (x, y, z) = (1, 2); } } public static class Extensions { public static void Deconstruct(this (int, int) self, out int x, out string y, out string z) { throw null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,25): error CS0029: Cannot implicitly convert type 'int' to 'string' // (x, y, z) = (1, 2); Diagnostic(ErrorCode.ERR_NoImplicitConv, "2").WithArguments("int", "string").WithLocation(8, 25), // (8,9): error CS8132: Cannot deconstruct a tuple of '2' elements into '3' variables. // (x, y, z) = (1, 2); Diagnostic(ErrorCode.ERR_DeconstructWrongCardinality, "(x, y, z) = (1, 2)").WithArguments("2", "3").WithLocation(8, 9) ); } [Fact] public void OverrideDeconstruct() { string source = @" class Base { public virtual void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } class C : Base { static void Main() { int x; string y; (x, y) = new C(); } public override void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; System.Console.WriteLine(""override""); } } "; var comp = CompileAndVerify(source, expectedOutput: "override", parseOptions: TestOptions.Regular.WithRefsFeature()); comp.VerifyDiagnostics(); } [Fact] public void DeconstructRefTuple() { string template = @" using System; class C { static void Main() { int VARIABLES; // int x1, x2, ... (VARIABLES) = (TUPLE).ToTuple(); // (x1, x2, ...) = (1, 2, ...).ToTuple(); System.Console.WriteLine(OUTPUT); } } "; for (int i = 2; i <= 21; i++) { var tuple = String.Join(", ", Enumerable.Range(1, i).Select(n => n.ToString())); var variables = String.Join(", ", Enumerable.Range(1, i).Select(n => $"x{n}")); var output = String.Join(@" + "" "" + ", Enumerable.Range(1, i).Select(n => $"x{n}")); var expected = String.Join(" ", Enumerable.Range(1, i).Select(n => n)); var source = template.Replace("VARIABLES", variables).Replace("TUPLE", tuple).Replace("OUTPUT", output); var comp = CompileAndVerify(source, expectedOutput: expected, parseOptions: TestOptions.Regular.WithRefsFeature()); comp.VerifyDiagnostics(); } } [Fact] public void DeconstructExtensionMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } } static class D { public static void Deconstruct(this C value, out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); } [Fact] public void DeconstructRefExtensionMethod() { // https://github.com/dotnet/csharplang/blob/main/meetings/2018/LDM-2018-01-24.md string source = @" struct C { static void Main() { long x; string y; var c = new C(); (x, y) = c; System.Console.WriteLine(x + "" "" + y); } } static class D { public static void Deconstruct(this ref C value, out int a, out string b) { a = 1; b = ""hello""; } } "; CreateCompilation(source).VerifyDiagnostics( // (10,9): error CS1510: A ref or out value must be an assignable variable // (x, y) = c; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x, y) = c").WithLocation(10, 9) ); } [Fact] public void DeconstructInExtensionMethod() { string source = @" struct C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } } static class D { public static void Deconstruct(this in C value, out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); } [Fact] public void UnderspecifiedDeconstructGenericExtensionMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); } } static class Extension { public static void Deconstruct<T>(this C value, out int a, out T b) { a = 2; b = default(T); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS0411: The type arguments for method 'Extension.Deconstruct<T>(C, out int, out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // (x, y) = new C(); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "new C()").WithArguments("Extension.Deconstruct<T>(C, out int, out T)").WithLocation(8, 18), // (8,18): error CS8129: No Deconstruct instance or extension method was found for type 'C', with 2 out parameters. // (x, y) = new C(); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 18) ); } [Fact] public void UnspecifiedGenericMethodIsNotCandidate() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); } } static class Extension { public static void Deconstruct<T>(this C value, out int a, out T b) { a = 2; b = default(T); } public static void Deconstruct(this C value, out int a, out string b) { a = 2; b = ""hello""; System.Console.Write(""Deconstructed""); } }"; var comp = CompileAndVerify(source, expectedOutput: "Deconstructed"); comp.VerifyDiagnostics(); } [Fact] public void DeconstructGenericExtensionMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C1<string>(); } } public class C1<T> { } static class Extension { public static void Deconstruct<T>(this C1<T> value, out int a, out T b) { a = 2; b = default(T); System.Console.WriteLine(""Deconstructed""); } } "; var comp = CompileAndVerify(source, expectedOutput: "Deconstructed"); comp.VerifyDiagnostics(); } [Fact] public void DeconstructGenericMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C1(); } } class C1 { public void Deconstruct<T>(out int a, out T b) { a = 2; b = default(T); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,18): error CS0411: The type arguments for method 'C1.Deconstruct<T>(out int, out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // (x, y) = new C1(); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "new C1()").WithArguments("C1.Deconstruct<T>(out int, out T)").WithLocation(9, 18), // (9,18): error CS8129: No Deconstruct instance or extension method was found for type 'C1', with 2 out parameters and a void return type. // (x, y) = new C1(); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C1()").WithArguments("C1", "2").WithLocation(9, 18) ); } [Fact] public void AmbiguousDeconstructGenericMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C1(); System.Console.Write($""{x} {y}""); } } class C1 { public void Deconstruct<T>(out int a, out T b) { a = 2; b = default(T); } public void Deconstruct(out int a, out string b) { a = 2; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "2 hello"); comp.VerifyDiagnostics(); } [Fact] public void NestedTupleAssignment() { string source = @" class C { static void Main() { long x; string y, z; (x, (y, z)) = ((int)1, (""a"", ""b"")); System.Console.WriteLine(x + "" "" + y + "" "" + z); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(x, (y, z))", lhs.ToString()); Assert.Equal("(System.Int64 x, (System.String y, System.String z))", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int64 x, (System.String y, System.String z))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); }; var comp = CompileAndVerify(source, expectedOutput: "1 a b", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void NestedTypelessTupleAssignment() { string source = @" class C { static void Main() { string x, y, z; (x, (y, z)) = (null, (null, null)); System.Console.WriteLine(""nothing"" + x + y + z); } } "; var comp = CompileAndVerify(source, expectedOutput: "nothing"); comp.VerifyDiagnostics(); } [Fact] public void NestedDeconstructAssignment() { string source = @" class C { static void Main() { int x; string y, z; (x, (y, z)) = new D1(); System.Console.WriteLine(x + "" "" + y + "" "" + z); } } class D1 { public void Deconstruct(out int item1, out D2 item2) { item1 = 1; item2 = new D2(); } } class D2 { public void Deconstruct(out string item1, out string item2) { item1 = ""a""; item2 = ""b""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 a b"); comp.VerifyDiagnostics(); } [Fact] public void NestedMixedAssignment1() { string source = @" class C { static void Main() { int x, y, z; (x, (y, z)) = (1, new D1()); System.Console.WriteLine(x + "" "" + y + "" "" + z); } } class D1 { public void Deconstruct(out int item1, out int item2) { item1 = 2; item2 = 3; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2 3"); comp.VerifyDiagnostics(); } [Fact] public void NestedMixedAssignment2() { string source = @" class C { static void Main() { int x; string y, z; (x, (y, z)) = new D1(); System.Console.WriteLine(x + "" "" + y + "" "" + z); } } class D1 { public void Deconstruct(out int item1, out (string, string) item2) { item1 = 1; item2 = (""a"", ""b""); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 a b"); comp.VerifyDiagnostics(); } [Fact] public void VerifyNestedExecutionOrder() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } int z { set { Console.WriteLine($""setZ""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; } C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; } static void Main() { C c = new C(); (c.getHolderForX().x, (c.getHolderForY().y, c.getHolderForZ().z)) = c.getDeconstructReceiver(); } public void Deconstruct(out D1 x, out C1 t) { x = new D1(); t = new C1(); Console.WriteLine(""Deconstruct1""); } } class C1 { public void Deconstruct(out D2 y, out D3 z) { y = new D2(); z = new D3(); Console.WriteLine(""Deconstruct2""); } } class D1 { public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } class D3 { public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; } } "; string expected = @"getHolderforX getHolderforY getHolderforZ getDeconstructReceiver Deconstruct1 Deconstruct2 Conversion1 Conversion2 Conversion3 setX setY setZ "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyNestedExecutionOrder_Conditional() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } int z { set { Console.WriteLine($""setZ""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; } C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; } static void Main() { C c = new C(); bool b = false; (c.getHolderForX().x, (c.getHolderForY().y, c.getHolderForZ().z)) = b ? default : c.getDeconstructReceiver(); } public void Deconstruct(out D1 x, out C1 t) { x = new D1(); t = new C1(); Console.WriteLine(""Deconstruct1""); } } class C1 { public void Deconstruct(out D2 y, out D3 z) { y = new D2(); z = new D3(); Console.WriteLine(""Deconstruct2""); } } class D1 { public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } class D3 { public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; } } "; string expected = @"getHolderforX getHolderforY getHolderforZ getDeconstructReceiver Deconstruct1 Deconstruct2 Conversion1 Conversion2 Conversion3 setX setY setZ "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyNestedExecutionOrder2() { string source = @" using System; class C { static LongInteger x1 { set { Console.WriteLine($""setX1 {value}""); } } static LongInteger x2 { set { Console.WriteLine($""setX2 {value}""); } } static LongInteger x3 { set { Console.WriteLine($""setX3 {value}""); } } static LongInteger x4 { set { Console.WriteLine($""setX4 {value}""); } } static LongInteger x5 { set { Console.WriteLine($""setX5 {value}""); } } static LongInteger x6 { set { Console.WriteLine($""setX6 {value}""); } } static LongInteger x7 { set { Console.WriteLine($""setX7 {value}""); } } static void Main() { ((x1, (x2, x3)), ((x4, x5), (x6, x7))) = Pair.Create(Pair.Create(new Integer(1), Pair.Create(new Integer(2), new Integer(3))), Pair.Create(Pair.Create(new Integer(4), new Integer(5)), Pair.Create(new Integer(6), new Integer(7)))); } } " + commonSource; string expected = @"Deconstructing ((1, (2, 3)), ((4, 5), (6, 7))) Deconstructing (1, (2, 3)) Deconstructing (2, 3) Deconstructing ((4, 5), (6, 7)) Deconstructing (4, 5) Deconstructing (6, 7) Converting 1 Converting 2 Converting 3 Converting 4 Converting 5 Converting 6 Converting 7 setX1 1 setX2 2 setX3 3 setX4 4 setX5 5 setX6 6 setX7 7"; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void MixOfAssignments() { string source = @" class C { static void Main() { long x; string y; C a, b, c; c = new C(); (x, y) = a = b = c; System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/12400")] [WorkItem(12400, "https://github.com/dotnet/roslyn/issues/12400")] public void AssignWithPostfixOperator() { string source = @" class C { int state = 1; static void Main() { long x; string y; C c = new C(); (x, y) = c++; System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = state; b = ""hello""; } public static C operator ++(C c1) { return new C() { state = 2 }; } } "; // https://github.com/dotnet/roslyn/issues/12400 // we expect "2 hello" instead, which means the evaluation order is wrong var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); } [Fact] [WorkItem(13631, "https://github.com/dotnet/roslyn/issues/13631")] public void DeconstructionDeclaration() { string source = @" class C { static void Main() { var (x1, x2) = (1, ""hello""); System.Console.WriteLine(x1 + "" "" + x2); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 32 (0x20) .maxstack 3 .locals init (int V_0, //x1 string V_1) //x2 IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldstr ""hello"" IL_0007: stloc.1 IL_0008: ldloca.s V_0 IL_000a: call ""string int.ToString()"" IL_000f: ldstr "" "" IL_0014: ldloc.1 IL_0015: call ""string string.Concat(string, string, string)"" IL_001a: call ""void System.Console.WriteLine(string)"" IL_001f: ret }"); } [Fact] public void NestedVarDeconstructionDeclaration() { string source = @" class C { static void Main() { var (x1, (x2, x3)) = (1, (2, ""hello"")); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().First(); Assert.Equal(@"var (x1, (x2, x3))", lhs.ToString()); Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhs).Symbol); var lhsNested = tree.GetRoot().DescendantNodes().OfType<ParenthesizedVariableDesignationSyntax>().ElementAt(1); Assert.Equal(@"(x2, x3)", lhsNested.ToString()); Assert.Null(model.GetTypeInfo(lhsNested).Type); Assert.Null(model.GetSymbolInfo(lhsNested).Symbol); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); }; var comp = CompileAndVerify(source, expectedOutput: "1 2 hello", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void NestedVarDeconstructionDeclaration_WithCSharp7_1() { string source = @" class C { static void Main() { (int x1, var (x2, (x3, x4)), var x5) = (1, (2, (3, ""hello"")), 5); System.Console.WriteLine($""{x1} {x2} {x3} {x4} {x5}""); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(int x1, var (x2, (x3, x4)), var x5)", lhs.ToString()); Assert.Equal("(System.Int32 x1, (System.Int32 x2, (System.Int32 x3, System.String x4)), System.Int32 x5)", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhs).Symbol); var x234 = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(1); Assert.Equal(@"var (x2, (x3, x4))", x234.ToString()); Assert.Equal("(System.Int32 x2, (System.Int32 x3, System.String x4))", model.GetTypeInfo(x234).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x234).Symbol); var x34 = tree.GetRoot().DescendantNodes().OfType<ParenthesizedVariableDesignationSyntax>().ElementAt(1); Assert.Equal(@"(x3, x4)", x34.ToString()); Assert.Null(model.GetTypeInfo(x34).Type); Assert.Null(model.GetSymbolInfo(x34).Symbol); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); var x4 = GetDeconstructionVariable(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForDeconstructionLocal(model, x4, x4Ref); var x5 = GetDeconstructionVariable(tree, "x5"); var x5Ref = GetReference(tree, "x5"); VerifyModelForDeconstructionLocal(model, x5, x5Ref); }; var comp = CompileAndVerify(source, expectedOutput: "1 2 3 hello 5", sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics(); } [Fact] public void NestedVarDeconstructionAssignment_WithCSharp7_1() { string source = @" class C { static void Main() { int x1, x2, x3; (x1, (x2, x3)) = (1, (2, 3)); System.Console.WriteLine($""{x1} {x2} {x3}""); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x123 = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(x1, (x2, x3))", x123.ToString()); Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.Int32 x3))", model.GetTypeInfo(x123).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x123).Symbol); var x23 = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(x2, x3)", x23.ToString()); Assert.Equal("(System.Int32 x2, System.Int32 x3)", model.GetTypeInfo(x23).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x23).Symbol); }; var comp = CompileAndVerify(source, expectedOutput: "1 2 3", sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics(); } [Fact] public void NestedVarDeconstructionDeclaration2() { string source = @" class C { static void Main() { (var x1, var (x2, x3)) = (1, (2, ""hello"")); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal("(var x1, var (x2, x3))", lhs.ToString()); Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhs).Symbol); var lhsNested = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(1); Assert.Equal("var (x2, x3)", lhsNested.ToString()); Assert.Equal("(System.Int32 x2, System.String x3)", model.GetTypeInfo(lhsNested).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 x2, System.String x3)", model.GetTypeInfo(lhsNested).ConvertedType.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhsNested).Symbol); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); }; var comp = CompileAndVerify(source, expectedOutput: "1 2 hello", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void NestedVarDeconstructionDeclarationWithCSharp7_1() { string source = @" class C { static void Main() { (var x1, byte _, var (x2, x3)) = (1, 2, (3, ""hello"")); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal("(var x1, byte _, var (x2, x3))", lhs.ToString()); Assert.Equal("(System.Int32 x1, System.Byte, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 x1, System.Byte, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhs).Symbol); var lhsNested = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(2); Assert.Equal("var (x2, x3)", lhsNested.ToString()); Assert.Equal("(System.Int32 x2, System.String x3)", model.GetTypeInfo(lhsNested).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhsNested).Symbol); }; var comp = CompileAndVerify(source, sourceSymbolValidator: validator, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyDiagnostics(); } [Fact] public void NestedDeconstructionDeclaration() { string source = @" class C { static void Main() { (int x1, (int x2, string x3)) = (1, (2, ""hello"")); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); }; var comp = CompileAndVerify(source, expectedOutput: "1 2 hello", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void VarMethodExists() { string source = @" class C { static void Main() { int x1 = 1; int x2 = 1; var (x1, x2); } static void var(int a, int b) { System.Console.WriteLine(""var""); } } "; var comp = CompileAndVerify(source, expectedOutput: "var"); comp.VerifyDiagnostics(); } [Fact] public void TypeMergingSuccess1() { string source = @" class C { static void Main() { (var (x1, x2), string x3) = ((1, 2), null); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; var comp = CompileAndVerify(source, expectedOutput: " 1 2"); comp.VerifyDiagnostics(); } [Fact] public void TypeMergingSuccess2() { string source = @" class C { static void Main() { (string x1, byte x2, var x3) = (null, 2, 3); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(string x1, byte x2, var x3)", lhs.ToString()); Assert.Equal("(System.String x1, System.Byte x2, System.Int32 x3)", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); var literal = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(null, 2, 3)", literal.ToString()); Assert.Null(model.GetTypeInfo(literal).Type); Assert.Equal("(System.String, System.Byte, System.Int32)", model.GetTypeInfo(literal).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(literal).Kind); }; var comp = CompileAndVerify(source, expectedOutput: " 2 3", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void TypeMergingSuccess3() { string source = @" class C { static void Main() { (string x1, var x2) = (null, (1, 2)); System.Console.WriteLine(x1 + "" "" + x2); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(string x1, var x2)", lhs.ToString()); Assert.Equal("(System.String x1, (System.Int32, System.Int32) x2)", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); var literal = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(null, (1, 2))", literal.ToString()); Assert.Null(model.GetTypeInfo(literal).Type); Assert.Equal("(System.String, (System.Int32, System.Int32))", model.GetTypeInfo(literal).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(literal).Kind); var nestedLiteral = literal.Arguments[1].Expression; Assert.Equal(@"(1, 2)", nestedLiteral.ToString()); Assert.Equal("(System.Int32, System.Int32)", model.GetTypeInfo(nestedLiteral).Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", model.GetTypeInfo(nestedLiteral).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(nestedLiteral).Kind); }; var comp = CompileAndVerify(source, expectedOutput: " (1, 2)", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void TypeMergingSuccess4() { string source = @" class C { static void Main() { ((string x1, byte x2, var x3), int x4) = (M(), 4); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4); } static (string, byte, int) M() { return (null, 2, 3); } } "; var comp = CompileAndVerify(source, expectedOutput: " 2 3 4"); comp.VerifyDiagnostics(); } [Fact] public void VarVarDeclaration() { string source = @" class C { static void Main() { (var (x1, x2), var x3) = Pair.Create(Pair.Create(1, ""hello""), 2); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } " + commonSource; string expected = @"Deconstructing ((1, hello), 2) Deconstructing (1, hello) 1 hello 2"; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); }; var comp = CompileAndVerify(source, expectedOutput: expected, parseOptions: TestOptions.Regular, sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } private static void VerifyModelForDeconstructionLocal(SemanticModel model, SingleVariableDesignationSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForDeconstruction(model, decl, LocalDeclarationKind.DeconstructionVariable, references); } private static void VerifyModelForLocal(SemanticModel model, SingleVariableDesignationSyntax decl, LocalDeclarationKind kind, params IdentifierNameSyntax[] references) { VerifyModelForDeconstruction(model, decl, kind, references); } private static void VerifyModelForDeconstructionForeach(SemanticModel model, SingleVariableDesignationSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForDeconstruction(model, decl, LocalDeclarationKind.ForEachIterationVariable, references); } private static void VerifyModelForDeconstruction(SemanticModel model, SingleVariableDesignationSyntax decl, LocalDeclarationKind kind, params IdentifierNameSyntax[] references) { var symbol = model.GetDeclaredSymbol(decl); Assert.Equal(decl.Identifier.ValueText, symbol.Name); Assert.Equal(kind, symbol.GetSymbol<LocalSymbol>().DeclarationKind); Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)decl)); Assert.Same(symbol, model.LookupSymbols(decl.SpanStart, name: decl.Identifier.ValueText).Single()); Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier.ValueText)); var local = symbol.GetSymbol<SourceLocalSymbol>(); var typeSyntax = GetTypeSyntax(decl); if (local.IsVar && local.Type.IsErrorType()) { Assert.Null(model.GetSymbolInfo(typeSyntax).Symbol); } else { if (typeSyntax != null) { Assert.Equal(local.Type.GetPublicSymbol(), model.GetSymbolInfo(typeSyntax).Symbol); } } foreach (var reference in references) { Assert.Same(symbol, model.GetSymbolInfo(reference).Symbol); Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: decl.Identifier.ValueText).Single()); Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier.ValueText)); Assert.Equal(local.Type.GetPublicSymbol(), model.GetTypeInfo(reference).Type); } } private static void VerifyModelForDeconstructionField(SemanticModel model, SingleVariableDesignationSyntax decl, params IdentifierNameSyntax[] references) { var field = (IFieldSymbol)model.GetDeclaredSymbol(decl); Assert.Equal(decl.Identifier.ValueText, field.Name); Assert.Equal(SymbolKind.Field, field.Kind); Assert.Same(field, model.GetDeclaredSymbol((SyntaxNode)decl)); Assert.Same(field, model.LookupSymbols(decl.SpanStart, name: decl.Identifier.ValueText).Single()); Assert.Equal(Accessibility.Private, field.DeclaredAccessibility); Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier.ValueText)); foreach (var reference in references) { Assert.Same(field, model.GetSymbolInfo(reference).Symbol); Assert.Same(field, model.LookupSymbols(reference.SpanStart, name: decl.Identifier.ValueText).Single()); Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier.ValueText)); Assert.Equal(field.Type, model.GetTypeInfo(reference).Type); } } private static TypeSyntax GetTypeSyntax(SingleVariableDesignationSyntax decl) { return (decl.Parent as DeclarationExpressionSyntax)?.Type; } private static SingleVariableDesignationSyntax GetDeconstructionVariable(SyntaxTree tree, string name) { return tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == name).Single(); } private static IEnumerable<DiscardDesignationSyntax> GetDiscardDesignations(SyntaxTree tree) { return tree.GetRoot().DescendantNodes().OfType<DiscardDesignationSyntax>(); } private static IEnumerable<IdentifierNameSyntax> GetDiscardIdentifiers(SyntaxTree tree) { return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(i => i.Identifier.ContextualKind() == SyntaxKind.UnderscoreToken); } private static IdentifierNameSyntax GetReference(SyntaxTree tree, string name) { return GetReferences(tree, name).Single(); } private static IdentifierNameSyntax[] GetReferences(SyntaxTree tree, string name, int count) { var nameRef = GetReferences(tree, name).ToArray(); Assert.Equal(count, nameRef.Length); return nameRef; } private static IEnumerable<IdentifierNameSyntax> GetReferences(SyntaxTree tree, string name) { return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == name); } [Fact] public void DeclarationWithActualVarType() { string source = @" class C { static void Main() { (var x1, int x2) = (new var(), 2); System.Console.WriteLine(x1 + "" "" + x2); } } class var { public override string ToString() { return ""var""; } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); // extra checks on x1 var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("var", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); // extra checks on x2 var x2Type = GetTypeSyntax(x2); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString()); }; var comp = CompileAndVerify(source, expectedOutput: "var 2", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void DeclarationWithImplicitVarType() { string source = @" class C { static void Main() { (var x1, var x2) = (1, 2); var (x3, x4) = (3, 4); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); var x4 = GetDeconstructionVariable(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForDeconstructionLocal(model, x4, x4Ref); // extra checks on x1 var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(x1Type)); var x34Var = (DeclarationExpressionSyntax)x3.Parent.Parent; Assert.Equal("var", x34Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x34Var.Type).Symbol); // The var in `var (x3, x4)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void DeclarationWithAliasedVarType() { string source = @" using var = D; class C { static void Main() { (var x1, int x2) = (new var(), 2); System.Console.WriteLine(x1 + "" "" + x2); } } class D { public override string ToString() { return ""var""; } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); // extra checks on x1 var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("D", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); var x1Alias = model.GetAliasInfo(x1Type); Assert.Equal(SymbolKind.NamedType, x1Alias.Target.Kind); Assert.Equal("D", x1Alias.Target.ToDisplayString()); // extra checks on x2 var x2Type = GetTypeSyntax(x2); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(x2Type)); }; var comp = CompileAndVerify(source, expectedOutput: "var 2", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void ForWithImplicitVarType() { string source = @" class C { static void Main() { for (var (x1, x2) = (1, 2); x1 < 2; (x1, x2) = (x1 + 1, x2 + 1)) { System.Console.WriteLine(x1 + "" "" + x2); } } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 4); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReferences(tree, "x2", 3); VerifyModelForDeconstructionLocal(model, x2, x2Ref); // extra check on var var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x12Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void ForWithVarDeconstructInitializersCanParse() { string source = @" using System; class C { static void Main() { int x3; for (var (x1, x2) = (1, 2), x3 = 3; true; ) { Console.WriteLine(x1); Console.WriteLine(x2); Console.WriteLine(x3); break; } } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); }; var comp = CompileAndVerify(source, expectedOutput: @"1 2 3", sourceSymbolValidator: validator); comp.VerifyDiagnostics( // this is permitted now, as it is just an assignment expression ); } [Fact] public void ForWithActualVarType() { string source = @" class C { static void Main() { for ((int x1, var x2) = (1, new var()); x1 < 2; x1++) { System.Console.WriteLine(x1 + "" "" + x2); } } } class var { public override string ToString() { return ""var""; } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 3); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); // extra checks on x1 var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); // extra checks on x2 var x2Type = GetTypeSyntax(x2); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind); Assert.Equal("var", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString()); }; var comp = CompileAndVerify(source, expectedOutput: "1 var", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void ForWithTypes() { string source = @" class C { static void Main() { for ((int x1, var x2) = (1, 2); x1 < 2; x1++) { System.Console.WriteLine(x1 + "" "" + x2); } } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 3); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); // extra checks on x1 var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); // extra checks on x2 var x2Type = GetTypeSyntax(x2); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString()); }; var comp = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void ForEachIEnumerableDeclarationWithImplicitVarType() { string source = @" using System.Collections.Generic; class C { static void Main() { foreach (var (x1, x2) in M()) { Print(x1, x2); } } static IEnumerable<(int, int)> M() { yield return (1, 2); } static void Print(object a, object b) { System.Console.WriteLine(a + "" "" + b); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); // extra check on var var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x12Var.Type.ToString()); Assert.Equal("(System.Int32 x1, System.Int32 x2)", model.GetTypeInfo(x12Var).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol // verify deconstruction info var deconstructionForeach = tree.GetRoot().DescendantNodes().OfType<ForEachVariableStatementSyntax>().Single(); var deconstructionInfo = model.GetDeconstructionInfo(deconstructionForeach); Assert.Null(deconstructionInfo.Method); Assert.Null(deconstructionInfo.Conversion); var nested = deconstructionInfo.Nested; Assert.Equal(2, nested.Length); Assert.Null(nested[0].Method); Assert.Equal(ConversionKind.Identity, nested[0].Conversion.Value.Kind); Assert.Empty(nested[0].Nested); Assert.Null(nested[1].Method); Assert.Equal(ConversionKind.Identity, nested[1].Conversion.Value.Kind); Assert.Empty(nested[1].Nested); }; var comp = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); var comp7_1 = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1); comp7_1.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 70 (0x46) .maxstack 2 .locals init (System.Collections.Generic.IEnumerator<System.ValueTuple<int, int>> V_0, int V_1, //x1 int V_2) //x2 IL_0000: call ""System.Collections.Generic.IEnumerable<System.ValueTuple<int, int>> C.M()"" IL_0005: callvirt ""System.Collections.Generic.IEnumerator<System.ValueTuple<int, int>> System.Collections.Generic.IEnumerable<System.ValueTuple<int, int>>.GetEnumerator()"" IL_000a: stloc.0 .try { IL_000b: br.s IL_0031 IL_000d: ldloc.0 IL_000e: callvirt ""System.ValueTuple<int, int> System.Collections.Generic.IEnumerator<System.ValueTuple<int, int>>.Current.get"" IL_0013: dup IL_0014: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0019: stloc.1 IL_001a: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_001f: stloc.2 IL_0020: ldloc.1 IL_0021: box ""int"" IL_0026: ldloc.2 IL_0027: box ""int"" IL_002c: call ""void C.Print(object, object)"" IL_0031: ldloc.0 IL_0032: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_0037: brtrue.s IL_000d IL_0039: leave.s IL_0045 } finally { IL_003b: ldloc.0 IL_003c: brfalse.s IL_0044 IL_003e: ldloc.0 IL_003f: callvirt ""void System.IDisposable.Dispose()"" IL_0044: endfinally } IL_0045: ret }"); } [Fact] public void ForEachSZArrayDeclarationWithImplicitVarType() { string source = @" class C { static void Main() { foreach (var (x1, x2) in M()) { System.Console.Write(x1 + "" "" + x2 + "" - ""); } } static (int, int)[] M() { return new[] { (1, 2), (3, 4) }; } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); var symbol = model.GetDeclaredSymbol(x1); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); // extra check on var var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x12Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 2 - 3 4 -", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 75 (0x4b) .maxstack 4 .locals init (System.ValueTuple<int, int>[] V_0, int V_1, int V_2, //x1 int V_3) //x2 IL_0000: call ""System.ValueTuple<int, int>[] C.M()"" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: stloc.1 IL_0008: br.s IL_0044 IL_000a: ldloc.0 IL_000b: ldloc.1 IL_000c: ldelem ""System.ValueTuple<int, int>"" IL_0011: dup IL_0012: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0017: stloc.2 IL_0018: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_001d: stloc.3 IL_001e: ldloca.s V_2 IL_0020: call ""string int.ToString()"" IL_0025: ldstr "" "" IL_002a: ldloca.s V_3 IL_002c: call ""string int.ToString()"" IL_0031: ldstr "" - "" IL_0036: call ""string string.Concat(string, string, string, string)"" IL_003b: call ""void System.Console.Write(string)"" IL_0040: ldloc.1 IL_0041: ldc.i4.1 IL_0042: add IL_0043: stloc.1 IL_0044: ldloc.1 IL_0045: ldloc.0 IL_0046: ldlen IL_0047: conv.i4 IL_0048: blt.s IL_000a IL_004a: ret }"); } [Fact] public void ForEachMDArrayDeclarationWithImplicitVarType() { string source = @" class C { static void Main() { foreach (var (x1, x2) in M()) { Print(x1, x2); } } static (int, int)[,] M() { return new (int, int)[2, 2] { { (1, 2), (3, 4) }, { (5, 6), (7, 8) } }; } static void Print(object a, object b) { System.Console.Write(a + "" "" + b + "" - ""); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); // extra check on var var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x12Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 2 - 3 4 - 5 6 - 7 8 -", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 106 (0x6a) .maxstack 3 .locals init (System.ValueTuple<int, int>[,] V_0, int V_1, int V_2, int V_3, int V_4, int V_5, //x1 int V_6) //x2 IL_0000: call ""System.ValueTuple<int, int>[,] C.M()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: callvirt ""int System.Array.GetUpperBound(int)"" IL_000d: stloc.1 IL_000e: ldloc.0 IL_000f: ldc.i4.1 IL_0010: callvirt ""int System.Array.GetUpperBound(int)"" IL_0015: stloc.2 IL_0016: ldloc.0 IL_0017: ldc.i4.0 IL_0018: callvirt ""int System.Array.GetLowerBound(int)"" IL_001d: stloc.3 IL_001e: br.s IL_0065 IL_0020: ldloc.0 IL_0021: ldc.i4.1 IL_0022: callvirt ""int System.Array.GetLowerBound(int)"" IL_0027: stloc.s V_4 IL_0029: br.s IL_005c IL_002b: ldloc.0 IL_002c: ldloc.3 IL_002d: ldloc.s V_4 IL_002f: call ""(int, int)[*,*].Get"" IL_0034: dup IL_0035: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_003a: stloc.s V_5 IL_003c: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0041: stloc.s V_6 IL_0043: ldloc.s V_5 IL_0045: box ""int"" IL_004a: ldloc.s V_6 IL_004c: box ""int"" IL_0051: call ""void C.Print(object, object)"" IL_0056: ldloc.s V_4 IL_0058: ldc.i4.1 IL_0059: add IL_005a: stloc.s V_4 IL_005c: ldloc.s V_4 IL_005e: ldloc.2 IL_005f: ble.s IL_002b IL_0061: ldloc.3 IL_0062: ldc.i4.1 IL_0063: add IL_0064: stloc.3 IL_0065: ldloc.3 IL_0066: ldloc.1 IL_0067: ble.s IL_0020 IL_0069: ret }"); } [Fact] public void ForEachStringDeclarationWithImplicitVarType() { string source = @" class C { static void Main() { foreach (var (x1, x2) in M()) { Print(x1, x2); } } static string M() { return ""123""; } static void Print(object a, object b) { System.Console.Write(a + "" "" + b + "" - ""); } } static class Extension { public static void Deconstruct(this char value, out int item1, out int item2) { item1 = item2 = System.Int32.Parse(value.ToString()); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); // extra check on var var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x12Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 1 - 2 2 - 3 3 - ", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 60 (0x3c) .maxstack 3 .locals init (string V_0, int V_1, int V_2, //x2 int V_3, int V_4) IL_0000: call ""string C.M()"" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: stloc.1 IL_0008: br.s IL_0032 IL_000a: ldloc.0 IL_000b: ldloc.1 IL_000c: callvirt ""char string.this[int].get"" IL_0011: ldloca.s V_3 IL_0013: ldloca.s V_4 IL_0015: call ""void Extension.Deconstruct(char, out int, out int)"" IL_001a: ldloc.3 IL_001b: ldloc.s V_4 IL_001d: stloc.2 IL_001e: box ""int"" IL_0023: ldloc.2 IL_0024: box ""int"" IL_0029: call ""void C.Print(object, object)"" IL_002e: ldloc.1 IL_002f: ldc.i4.1 IL_0030: add IL_0031: stloc.1 IL_0032: ldloc.1 IL_0033: ldloc.0 IL_0034: callvirt ""int string.Length.get"" IL_0039: blt.s IL_000a IL_003b: ret }"); } [Fact] [WorkItem(22495, "https://github.com/dotnet/roslyn/issues/22495")] public void ForEachCollectionSymbol() { string source = @" using System.Collections.Generic; class Deconstructable { void M(IEnumerable<Deconstructable> x) { foreach (var (y1, y2) in x) { } } void Deconstruct(out int i, out int j) { i = 0; j = 0; } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var collection = tree.GetRoot().DescendantNodes().OfType<ForEachVariableStatementSyntax>().Single().Expression; Assert.Equal("x", collection.ToString()); var symbol = model.GetSymbolInfo(collection).Symbol; Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal("x", symbol.Name); Assert.Equal("System.Collections.Generic.IEnumerable<Deconstructable> x", symbol.ToTestDisplayString()); } [Fact] public void ForEachIEnumerableDeclarationWithNesting() { string source = @" using System.Collections.Generic; class C { static void Main() { foreach ((int x1, var (x2, x3), (int x4, int x5)) in M()) { System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4 + "" "" + x5 + "" - ""); } } static IEnumerable<(int, (int, int), (int, int))> M() { yield return (1, (2, 3), (4, 5)); yield return (6, (7, 8), (9, 10)); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionForeach(model, x3, x3Ref); var x4 = GetDeconstructionVariable(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForDeconstructionForeach(model, x4, x4Ref); var x5 = GetDeconstructionVariable(tree, "x5"); var x5Ref = GetReference(tree, "x5"); VerifyModelForDeconstructionForeach(model, x5, x5Ref); // extra check on var var x23Var = (DeclarationExpressionSyntax)x2.Parent.Parent; Assert.Equal("var", x23Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x23Var.Type).Symbol); // The var in `var (x2, x3)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4 5 - 6 7 8 9 10 -", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void ForEachSZArrayDeclarationWithNesting() { string source = @" class C { static void Main() { foreach ((int x1, var (x2, x3), (int x4, int x5)) in M()) { System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4 + "" "" + x5 + "" - ""); } } static (int, (int, int), (int, int))[] M() { return new[] { (1, (2, 3), (4, 5)), (6, (7, 8), (9, 10)) }; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4 5 - 6 7 8 9 10 -"); comp.VerifyDiagnostics(); } [Fact] public void ForEachMDArrayDeclarationWithNesting() { string source = @" class C { static void Main() { foreach ((int x1, var (x2, x3), (int x4, int x5)) in M()) { System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4 + "" "" + x5 + "" - ""); } } static (int, (int, int), (int, int))[,] M() { return new(int, (int, int), (int, int))[1, 2] { { (1, (2, 3), (4, 5)), (6, (7, 8), (9, 10)) } }; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4 5 - 6 7 8 9 10 -"); comp.VerifyDiagnostics(); } [Fact] public void ForEachStringDeclarationWithNesting() { string source = @" class C { static void Main() { foreach ((int x1, var (x2, x3)) in M()) { System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" - ""); } } static string M() { return ""12""; } } static class Extension { public static void Deconstruct(this char value, out int item1, out (int, int) item2) { item1 = System.Int32.Parse(value.ToString()); item2 = (item1, item1); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 1 1 - 2 2 2 - "); comp.VerifyDiagnostics(); } [Fact] public void DeconstructExtensionOnInterface() { string source = @" public interface Interface { } class C : Interface { static void Main() { var (x, y) = new C(); System.Console.Write($""{x} {y}""); } } static class Extension { public static void Deconstruct(this Interface value, out int item1, out string item2) { item1 = 42; item2 = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "42 hello"); comp.VerifyDiagnostics(); } [Fact] public void ForEachIEnumerableDeclarationWithDeconstruct() { string source = @" using System.Collections.Generic; class C { static void Main() { foreach ((long x1, var (x2, x3)) in M()) { Print(x1, x2, x3); } } static IEnumerable<Pair<int, Pair<int, int>>> M() { yield return Pair.Create(1, Pair.Create(2, 3)); yield return Pair.Create(4, Pair.Create(5, 6)); } static void Print(object a, object b, object c) { System.Console.WriteLine(a + "" "" + b + "" "" + c); } } " + commonSource; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionForeach(model, x3, x3Ref); // extra check on var var x23Var = (DeclarationExpressionSyntax)x2.Parent.Parent; Assert.Equal("var", x23Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x23Var.Type).Symbol); // The var in `var (x2, x3)` has no symbol }; string expected = @"Deconstructing (1, (2, 3)) Deconstructing (2, 3) 1 2 3 Deconstructing (4, (5, 6)) Deconstructing (5, 6) 4 5 6"; var comp = CompileAndVerify(source, expectedOutput: expected, sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 90 (0x5a) .maxstack 3 .locals init (System.Collections.Generic.IEnumerator<Pair<int, Pair<int, int>>> V_0, int V_1, //x2 int V_2, //x3 int V_3, Pair<int, int> V_4, int V_5, int V_6) IL_0000: call ""System.Collections.Generic.IEnumerable<Pair<int, Pair<int, int>>> C.M()"" IL_0005: callvirt ""System.Collections.Generic.IEnumerator<Pair<int, Pair<int, int>>> System.Collections.Generic.IEnumerable<Pair<int, Pair<int, int>>>.GetEnumerator()"" IL_000a: stloc.0 .try { IL_000b: br.s IL_0045 IL_000d: ldloc.0 IL_000e: callvirt ""Pair<int, Pair<int, int>> System.Collections.Generic.IEnumerator<Pair<int, Pair<int, int>>>.Current.get"" IL_0013: ldloca.s V_3 IL_0015: ldloca.s V_4 IL_0017: callvirt ""void Pair<int, Pair<int, int>>.Deconstruct(out int, out Pair<int, int>)"" IL_001c: ldloc.s V_4 IL_001e: ldloca.s V_5 IL_0020: ldloca.s V_6 IL_0022: callvirt ""void Pair<int, int>.Deconstruct(out int, out int)"" IL_0027: ldloc.3 IL_0028: conv.i8 IL_0029: ldloc.s V_5 IL_002b: stloc.1 IL_002c: ldloc.s V_6 IL_002e: stloc.2 IL_002f: box ""long"" IL_0034: ldloc.1 IL_0035: box ""int"" IL_003a: ldloc.2 IL_003b: box ""int"" IL_0040: call ""void C.Print(object, object, object)"" IL_0045: ldloc.0 IL_0046: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_004b: brtrue.s IL_000d IL_004d: leave.s IL_0059 } finally { IL_004f: ldloc.0 IL_0050: brfalse.s IL_0058 IL_0052: ldloc.0 IL_0053: callvirt ""void System.IDisposable.Dispose()"" IL_0058: endfinally } IL_0059: ret } "); } [Fact] public void ForEachSZArrayDeclarationWithDeconstruct() { string source = @" class C { static void Main() { foreach ((int x1, var (x2, x3)) in M()) { System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } static Pair<int, Pair<int, int>>[] M() { return new[] { Pair.Create(1, Pair.Create(2, 3)), Pair.Create(4, Pair.Create(5, 6)) }; } } " + commonSource; string expected = @"Deconstructing (1, (2, 3)) Deconstructing (2, 3) 1 2 3 Deconstructing (4, (5, 6)) Deconstructing (5, 6) 4 5 6"; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void ForEachMDArrayDeclarationWithDeconstruct() { string source = @" class C { static void Main() { foreach ((int x1, var (x2, x3)) in M()) { System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } static Pair<int, Pair<int, int>>[,] M() { return new Pair<int, Pair<int, int>> [1, 2] { { Pair.Create(1, Pair.Create(2, 3)), Pair.Create(4, Pair.Create(5, 6)) } }; } } " + commonSource; string expected = @"Deconstructing (1, (2, 3)) Deconstructing (2, 3) 1 2 3 Deconstructing (4, (5, 6)) Deconstructing (5, 6) 4 5 6"; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void ForEachWithExpressionBody() { string source = @" class C { static void Main() { foreach (var (x1, x2) in new[] { (1, 2), (3, 4) }) System.Console.Write(x1 + "" "" + x2 + "" - ""); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2 - 3 4 -"); comp.VerifyDiagnostics(); } [Fact] public void ForEachCreatesNewVariables() { string source = @" class C { static void Main() { var lambdas = new System.Action[2]; int index = 0; foreach (var (x1, x2) in M()) { lambdas[index] = () => { System.Console.Write(x1 + "" ""); }; index++; } lambdas[0](); lambdas[1](); } static (int, int)[] M() { return new[] { (0, 0), (10, 10) }; } } "; var comp = CompileAndVerify(source, expectedOutput: "0 10 "); comp.VerifyDiagnostics(); } [Fact] public void TupleDeconstructionIntoDynamicArrayIndexer() { string source = @" class C { static void Main() { dynamic x = new string[] { """", """" }; M(x); System.Console.WriteLine($""{x[0]} {x[1]}""); } static void M(dynamic x) { (x[0], x[1]) = (""hello"", ""world""); } } "; var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void IntTupleDeconstructionIntoDynamicArrayIndexer() { string source = @" class C { static void Main() { dynamic x = new int[] { 1, 2 }; M(x); System.Console.WriteLine($""{x[0]} {x[1]}""); } static void M(dynamic x) { (x[0], x[1]) = (3, 4); } } "; var comp = CompileAndVerify(source, expectedOutput: "3 4", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DeconstructionIntoDynamicArrayIndexer() { string source = @" class C { static void Main() { dynamic x = new string[] { """", """" }; M(x); System.Console.WriteLine($""{x[0]} {x[1]}""); } static void M(dynamic x) { (x[0], x[1]) = new C(); } public void Deconstruct(out string a, out string b) { a = ""hello""; b = ""world""; } } "; var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void TupleDeconstructionIntoDynamicArray() { string source = @" class C { static void Main() { dynamic[] x = new string[] { """", """" }; M(x); System.Console.WriteLine($""{x[0]} {x[1]}""); } static void M(dynamic[] x) { (x[0], x[1]) = (""hello"", ""world""); } } "; var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DeconstructionIntoDynamicArray() { string source = @" class C { static void Main() { dynamic[] x = new string[] { """", """" }; M(x); System.Console.WriteLine($""{x[0]} {x[1]}""); } static void M(dynamic[] x) { (x[0], x[1]) = new C(); } public void Deconstruct(out string a, out string b) { a = ""hello""; b = ""world""; } } "; var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DeconstructionIntoDynamicMember() { string source = @" class C { static void Main() { dynamic x = System.ValueTuple.Create(1, 2); (x.Item1, x.Item2) = new C(); System.Console.WriteLine($""{x.Item1} {x.Item2}""); } public void Deconstruct(out int a, out int b) { a = 3; b = 4; } } "; var comp = CompileAndVerify(source, expectedOutput: "3 4", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void FieldAndLocalWithSameName() { string source = @" class C { public int x = 3; static void Main() { new C().M(); } void M() { var (x, y) = (1, 2); System.Console.Write($""{x} {y} {this.x}""); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2 3"); comp.VerifyDiagnostics(); } [Fact] public void NoGlobalDeconstructionUnlessScript() { string source = @" class C { var (x, y) = (1, 2); } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,11): error CS1001: Identifier expected // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_IdentifierExpected, ",").WithLocation(4, 11), // (4,14): error CS1001: Identifier expected // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 14), // (4,16): error CS1002: ; expected // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_SemicolonExpected, "=").WithLocation(4, 16), // (4,16): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(4, 16), // (4,19): error CS1031: Type expected // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_TypeExpected, "1").WithLocation(4, 19), // (4,19): error CS8124: Tuple must contain at least two elements. // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_TupleTooFewElements, "1").WithLocation(4, 19), // (4,19): error CS1026: ) expected // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_CloseParenExpected, "1").WithLocation(4, 19), // (4,19): error CS1519: Invalid token '1' in class, record, struct, or interface member declaration // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "1").WithArguments("1").WithLocation(4, 19), // (4,5): error CS1520: Method must have a return type // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_MemberNeedsType, "var").WithLocation(4, 5), // (4,5): error CS0501: 'C.C(x, y)' must declare a body because it is not marked abstract, extern, or partial // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "var").WithArguments("C.C(x, y)").WithLocation(4, 5), // (4,10): error CS0246: The type or namespace name 'x' could not be found (are you missing a using directive or an assembly reference?) // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "x").WithArguments("x").WithLocation(4, 10), // (4,13): error CS0246: The type or namespace name 'y' could not be found (are you missing a using directive or an assembly reference?) // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "y").WithArguments("y").WithLocation(4, 13) ); var nodes = comp.SyntaxTrees[0].GetCompilationUnitRoot().DescendantNodesAndSelf(); Assert.False(nodes.Any(n => n.Kind() == SyntaxKind.SimpleAssignmentExpression)); } [Fact] public void SimpleDeconstructionInScript() { var source = @" using alias = System.Int32; (string x, alias y) = (""hello"", 42); System.Console.Write($""{x} {y}""); "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xSymbol = model.GetDeclaredSymbol(x); var xRef = GetReference(tree, "x"); Assert.Equal("System.String Script.x", xSymbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x, xRef); var y = GetDeconstructionVariable(tree, "y"); var ySymbol = model.GetDeclaredSymbol(y); var yRef = GetReference(tree, "y"); Assert.Equal("System.Int32 Script.y", ySymbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, y, yRef); // extra checks on x var xType = GetTypeSyntax(x); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(xType).Symbol.Kind); Assert.Equal("string", model.GetSymbolInfo(xType).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(xType)); // extra checks on y var yType = GetTypeSyntax(y); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(yType).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(yType).Symbol.ToDisplayString()); Assert.Equal("alias=System.Int32", model.GetAliasInfo(yType).ToTestDisplayString()); }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42", sourceSymbolValidator: validator); verifier.VerifyIL("<<Initialize>>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 129 (0x81) .maxstack 3 .locals init (int V_0, object V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""int <<Initialize>>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldarg.0 IL_0008: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_000d: ldstr ""hello"" IL_0012: stfld ""string x"" IL_0017: ldarg.0 IL_0018: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_001d: ldc.i4.s 42 IL_001f: stfld ""int y"" IL_0024: ldstr ""{0} {1}"" IL_0029: ldarg.0 IL_002a: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_002f: ldfld ""string x"" IL_0034: ldarg.0 IL_0035: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_003a: ldfld ""int y"" IL_003f: box ""int"" IL_0044: call ""string string.Format(string, object, object)"" IL_0049: call ""void System.Console.Write(string)"" IL_004e: nop IL_004f: ldnull IL_0050: stloc.1 IL_0051: leave.s IL_006b } catch System.Exception { IL_0053: stloc.2 IL_0054: ldarg.0 IL_0055: ldc.i4.s -2 IL_0057: stfld ""int <<Initialize>>d__0.<>1__state"" IL_005c: ldarg.0 IL_005d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0062: ldloc.2 IL_0063: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)"" IL_0068: nop IL_0069: leave.s IL_0080 } IL_006b: ldarg.0 IL_006c: ldc.i4.s -2 IL_006e: stfld ""int <<Initialize>>d__0.<>1__state"" IL_0073: ldarg.0 IL_0074: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0079: ldloc.1 IL_007a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)"" IL_007f: nop IL_0080: ret }"); } [Fact] public void GlobalDeconstructionOutsideScript() { var source = @" (string x, int y) = (""hello"", 42); System.Console.Write(x); System.Console.Write(y); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var nodes = comp.SyntaxTrees[0].GetCompilationUnitRoot().DescendantNodesAndSelf(); Assert.True(nodes.Any(n => n.Kind() == SyntaxKind.SimpleAssignmentExpression)); CompileAndVerify(comp, expectedOutput: "hello42"); } [Fact] public void NestedDeconstructionInScript() { var source = @" (string x, (int y, int z)) = (""hello"", (42, 43)); System.Console.Write($""{x} {y} {z}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 43"); } [Fact] public void VarDeconstructionInScript() { var source = @" (var x, var y) = (""hello"", 42); System.Console.Write($""{x} {y}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42"); } [Fact] public void NestedVarDeconstructionInScript() { var source = @" (var x1, var (x2, x3)) = (""hello"", (42, 43)); System.Console.Write($""{x1} {x2} {x3}""); "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("System.String Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Symbol = model.GetDeclaredSymbol(x2); var x2Ref = GetReference(tree, "x2"); Assert.Equal("System.Int32 Script.x2", x2Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x2, x2Ref); // extra checks on x1's var var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("string", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(x1Type)); // extra check on x2 and x3's var var x23Var = (DeclarationExpressionSyntax)x2.Parent.Parent; Assert.Equal("var", x23Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x23Var.Type).Symbol); // The var in `var (x2, x3)` has no symbol }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 43", sourceSymbolValidator: validator); } [Fact] public void EvaluationOrderForDeconstructionInScript() { var source = @" (int, int) M(out int x) { x = 1; return (2, 3); } var (x2, x3) = M(out var x1); System.Console.Write($""{x1} {x2} {x3}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "1 2 3"); verifier.VerifyIL("<<Initialize>>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 178 (0xb2) .maxstack 4 .locals init (int V_0, object V_1, System.ValueTuple<int, int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int <<Initialize>>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldarg.0 IL_0008: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_000d: ldarg.0 IL_000e: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_0013: ldflda ""int x1"" IL_0018: call ""System.ValueTuple<int, int> M(out int)"" IL_001d: stloc.2 IL_001e: ldarg.0 IL_001f: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_0024: ldloc.2 IL_0025: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_002a: stfld ""int x2"" IL_002f: ldarg.0 IL_0030: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_0035: ldloc.2 IL_0036: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_003b: stfld ""int x3"" IL_0040: ldstr ""{0} {1} {2}"" IL_0045: ldarg.0 IL_0046: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_004b: ldfld ""int x1"" IL_0050: box ""int"" IL_0055: ldarg.0 IL_0056: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_005b: ldfld ""int x2"" IL_0060: box ""int"" IL_0065: ldarg.0 IL_0066: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_006b: ldfld ""int x3"" IL_0070: box ""int"" IL_0075: call ""string string.Format(string, object, object, object)"" IL_007a: call ""void System.Console.Write(string)"" IL_007f: nop IL_0080: ldnull IL_0081: stloc.1 IL_0082: leave.s IL_009c } catch System.Exception { IL_0084: stloc.3 IL_0085: ldarg.0 IL_0086: ldc.i4.s -2 IL_0088: stfld ""int <<Initialize>>d__0.<>1__state"" IL_008d: ldarg.0 IL_008e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0093: ldloc.3 IL_0094: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)"" IL_0099: nop IL_009a: leave.s IL_00b1 } IL_009c: ldarg.0 IL_009d: ldc.i4.s -2 IL_009f: stfld ""int <<Initialize>>d__0.<>1__state"" IL_00a4: ldarg.0 IL_00a5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_00aa: ldloc.1 IL_00ab: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)"" IL_00b0: nop IL_00b1: ret } "); } [Fact] public void DeconstructionForEachInScript() { var source = @" foreach ((string x1, var (x2, x3)) in new[] { (""hello"", (42, ""world"")) }) { System.Console.Write($""{x1} {x2} {x3}""); } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); Assert.Equal("System.String x1", x1Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, x1Symbol.Kind); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Symbol = model.GetDeclaredSymbol(x2); Assert.Equal("System.Int32 x2", x2Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, x2Symbol.Kind); }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 world", sourceSymbolValidator: validator); } [Fact] public void DeconstructionInForLoopInScript() { var source = @" for ((string x1, var (x2, x3)) = (""hello"", (42, ""world"")); ; ) { System.Console.Write($""{x1} {x2} {x3}""); break; } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); Assert.Equal("System.String x1", x1Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, x1Symbol.Kind); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Symbol = model.GetDeclaredSymbol(x2); Assert.Equal("System.Int32 x2", x2Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, x2Symbol.Kind); }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 world", sourceSymbolValidator: validator); } [Fact] public void DeconstructionInCSharp6Script() { var source = @" var (x, y) = (1, 2); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp6), options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (2,5): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(x, y)").WithArguments("tuples", "7.0").WithLocation(2, 5), // (2,14): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7 or greater. // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(1, 2)").WithArguments("tuples", "7.0").WithLocation(2, 14) ); } [Fact] public void InvalidDeconstructionInScript() { var source = @" int (x, y) = (1, 2); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (2,5): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'. // int (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x, y)").WithLocation(2, 5) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xSymbol = model.GetDeclaredSymbol(x); Assert.Equal("System.Int32 Script.x", xSymbol.ToTestDisplayString()); var xType = ((IFieldSymbol)xSymbol).Type; Assert.False(xType.IsErrorType()); Assert.Equal("System.Int32", xType.ToTestDisplayString()); var y = GetDeconstructionVariable(tree, "y"); var ySymbol = model.GetDeclaredSymbol(y); Assert.Equal("System.Int32 Script.y", ySymbol.ToTestDisplayString()); var yType = ((IFieldSymbol)ySymbol).Type; Assert.False(yType.IsErrorType()); Assert.Equal("System.Int32", yType.ToTestDisplayString()); } [Fact] public void InvalidDeconstructionInScript_2() { var source = @" (int (x, y), int z) = ((1, 2), 3); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (2,6): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'. // (int (x, y), int z) = ((1, 2), 3); Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x, y)").WithLocation(2, 6) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xSymbol = model.GetDeclaredSymbol(x); Assert.Equal("System.Int32 Script.x", xSymbol.ToTestDisplayString()); var xType = ((IFieldSymbol)xSymbol).Type; Assert.False(xType.IsErrorType()); Assert.Equal("System.Int32", xType.ToTestDisplayString()); var y = GetDeconstructionVariable(tree, "y"); var ySymbol = model.GetDeclaredSymbol(y); Assert.Equal("System.Int32 Script.y", ySymbol.ToTestDisplayString()); var yType = ((IFieldSymbol)ySymbol).Type; Assert.False(yType.IsErrorType()); Assert.Equal("System.Int32", yType.ToTestDisplayString()); } [Fact] public void NameConflictInDeconstructionInScript() { var source = @" int x1; var (x1, x2) = (1, 2); System.Console.Write(x1); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (3,6): error CS0102: The type 'Script' already contains a definition for 'x1' // var (x1, x2) = (1, 2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x1").WithArguments("Script", "x1").WithLocation(3, 6), // (4,22): error CS0229: Ambiguity between 'x1' and 'x1' // System.Console.Write(x1); Diagnostic(ErrorCode.ERR_AmbigMember, "x1").WithArguments("x1", "x1").WithLocation(4, 22) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var firstX1 = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "x1").Single(); var firstX1Symbol = model.GetDeclaredSymbol(firstX1); Assert.Equal("System.Int32 Script.x1", firstX1Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, firstX1Symbol.Kind); var secondX1 = GetDeconstructionVariable(tree, "x1"); var secondX1Symbol = model.GetDeclaredSymbol(secondX1); Assert.Equal("System.Int32 Script.x1", secondX1Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, secondX1Symbol.Kind); Assert.NotEqual(firstX1Symbol, secondX1Symbol); } [Fact] public void NameConflictInDeconstructionInScript2() { var source = @" var (x, y) = (1, 2); var (z, y) = (1, 2); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (3,9): error CS0102: The type 'Script' already contains a definition for 'y' // var (z, y) = (1, 2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "y").WithArguments("Script", "y").WithLocation(3, 9) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var firstY = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "y").First(); var firstYSymbol = model.GetDeclaredSymbol(firstY); Assert.Equal("System.Int32 Script.y", firstYSymbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, firstYSymbol.Kind); var secondY = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "y").ElementAt(1); var secondYSymbol = model.GetDeclaredSymbol(secondY); Assert.Equal("System.Int32 Script.y", secondYSymbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, secondYSymbol.Kind); Assert.NotEqual(firstYSymbol, secondYSymbol); } [Fact] public void NameConflictInDeconstructionInScript3() { var source = @" var (x, (y, x)) = (1, (2, ""hello"")); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (2,13): error CS0102: The type 'Script' already contains a definition for 'x' // var (x, (y, x)) = (1, (2, "hello")); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x").WithArguments("Script", "x").WithLocation(2, 13) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var firstX = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "x").First(); var firstXSymbol = model.GetDeclaredSymbol(firstX); Assert.Equal("System.Int32 Script.x", firstXSymbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, firstXSymbol.Kind); var secondX = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "x").ElementAt(1); var secondXSymbol = model.GetDeclaredSymbol(secondX); Assert.Equal("System.String Script.x", secondXSymbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, secondXSymbol.Kind); Assert.NotEqual(firstXSymbol, secondXSymbol); } [Fact] public void UnassignedUsedInDeconstructionInScript() { var source = @" System.Console.Write(x); var (x, y) = (1, 2); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "0"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xSymbol = model.GetDeclaredSymbol(x); var xRef = GetReference(tree, "x"); Assert.Equal("System.Int32 Script.x", xSymbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x, xRef); var xType = ((IFieldSymbol)xSymbol).Type; Assert.False(xType.IsErrorType()); Assert.Equal("System.Int32", xType.ToTestDisplayString()); } [Fact] public void FailedInferenceInDeconstructionInScript() { var source = @" var (x, y) = (1, null); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.GetDeclarationDiagnostics().Verify( // (2,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = (1, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(2, 6), // (2,9): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = (1, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(2, 9) ); comp.VerifyDiagnostics( // (2,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = (1, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(2, 6), // (2,9): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = (1, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(2, 9) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xSymbol = model.GetDeclaredSymbol(x); Assert.Equal("var Script.x", xSymbol.ToTestDisplayString()); var xType = xSymbol.GetSymbol<FieldSymbol>().TypeWithAnnotations; Assert.True(xType.Type.IsErrorType()); Assert.Equal("var", xType.ToTestDisplayString()); var xTypeISymbol = xType.Type.GetPublicSymbol(); Assert.Equal(SymbolKind.ErrorType, xTypeISymbol.Kind); var y = GetDeconstructionVariable(tree, "y"); var ySymbol = model.GetDeclaredSymbol(y); Assert.Equal("var Script.y", ySymbol.ToTestDisplayString()); var yType = ((IFieldSymbol)ySymbol).Type; Assert.True(yType.IsErrorType()); Assert.Equal("var", yType.ToTestDisplayString()); } [Fact] public void FailedCircularInferenceInDeconstructionInScript() { var source = @" var (x1, x2) = (x2, x1); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.GetDeclarationDiagnostics().Verify( // (2,10): error CS7019: Type of 'x2' cannot be inferred since its initializer directly or indirectly refers to the definition. // var (x1, x2) = (x2, x1); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x2").WithArguments("x2").WithLocation(2, 10), // (2,6): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // var (x1, x2) = (x2, x1); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 6) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("var Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x1Type = ((IFieldSymbol)x1Symbol).Type; Assert.True(x1Type.IsErrorType()); Assert.Equal("var", x1Type.Name); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Symbol = model.GetDeclaredSymbol(x2); var x2Ref = GetReference(tree, "x2"); Assert.Equal("var Script.x2", x2Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x2, x2Ref); var x2Type = ((IFieldSymbol)x2Symbol).Type; Assert.True(x2Type.IsErrorType()); Assert.Equal("var", x2Type.Name); } [Fact] public void FailedCircularInferenceInDeconstructionInScript2() { var source = @" var (x1, x2) = (y1, y2); var (y1, y2) = (x1, x2); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.GetDeclarationDiagnostics().Verify( // (3,6): error CS7019: Type of 'y1' cannot be inferred since its initializer directly or indirectly refers to the definition. // var (y1, y2) = (x1, x2); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "y1").WithArguments("y1").WithLocation(3, 6), // (2,6): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // var (x1, x2) = (y1, y2); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 6), // (2,10): error CS7019: Type of 'x2' cannot be inferred since its initializer directly or indirectly refers to the definition. // var (x1, x2) = (y1, y2); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x2").WithArguments("x2").WithLocation(2, 10) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("var Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x1Type = ((IFieldSymbol)x1Symbol).Type; Assert.True(x1Type.IsErrorType()); Assert.Equal("var", x1Type.Name); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Symbol = model.GetDeclaredSymbol(x2); var x2Ref = GetReference(tree, "x2"); Assert.Equal("var Script.x2", x2Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x2, x2Ref); var x2Type = ((IFieldSymbol)x2Symbol).Type; Assert.True(x2Type.IsErrorType()); Assert.Equal("var", x2Type.Name); } [Fact] public void VarAliasInVarDeconstructionInScript() { var source = @" using var = System.Byte; var (x1, (x2, x3)) = (1, (2, 3)); System.Console.Write($""{x1} {x2} {x3}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (3,5): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'. // var (x1, (x2, x3)) = (1, (2, 3)); Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x1, (x2, x3))").WithLocation(3, 5) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("System.Byte Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Symbol = model.GetDeclaredSymbol(x3); var x3Ref = GetReference(tree, "x3"); Assert.Equal("System.Byte Script.x3", x3Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x3, x3Ref); // extra check on var var x123Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x123Var.Type.ToString()); Assert.Null(model.GetTypeInfo(x123Var.Type).Type); Assert.Null(model.GetSymbolInfo(x123Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol } [Fact] public void VarTypeInVarDeconstructionInScript() { var source = @" class var { public static implicit operator var(int i) { return null; } } var (x1, (x2, x3)) = (1, (2, 3)); System.Console.Write($""{x1} {x2} {x3}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (6,5): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'. // var (x1, (x2, x3)) = (1, (2, 3)); Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x1, (x2, x3))").WithLocation(6, 5) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("Script.var Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Symbol = model.GetDeclaredSymbol(x3); var x3Ref = GetReference(tree, "x3"); Assert.Equal("Script.var Script.x3", x3Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x3, x3Ref); // extra check on var var x123Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x123Var.Type.ToString()); Assert.Null(model.GetTypeInfo(x123Var.Type).Type); Assert.Null(model.GetSymbolInfo(x123Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol } [Fact] public void VarAliasInTypedDeconstructionInScript() { var source = @" using var = System.Byte; (var x1, (var x2, var x3)) = (1, (2, 3)); System.Console.Write($""{x1} {x2} {x3}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1 2 3"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("System.Byte Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Symbol = model.GetDeclaredSymbol(x3); var x3Ref = GetReference(tree, "x3"); Assert.Equal("System.Byte Script.x3", x3Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x3, x3Ref); // extra checks on x1's var var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("byte", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); var x1Alias = model.GetAliasInfo(x1Type); Assert.Equal(SymbolKind.NamedType, x1Alias.Target.Kind); Assert.Equal("byte", x1Alias.Target.ToDisplayString()); // extra checks on x3's var var x3Type = GetTypeSyntax(x3); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x3Type).Symbol.Kind); Assert.Equal("byte", model.GetSymbolInfo(x3Type).Symbol.ToDisplayString()); var x3Alias = model.GetAliasInfo(x3Type); Assert.Equal(SymbolKind.NamedType, x3Alias.Target.Kind); Assert.Equal("byte", x3Alias.Target.ToDisplayString()); } [Fact] public void VarTypeInTypedDeconstructionInScript() { var source = @" class var { public static implicit operator var(int i) { return new var(); } public override string ToString() { return ""var""; } } (var x1, (var x2, var x3)) = (1, (2, 3)); System.Console.Write($""{x1} {x2} {x3}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "var var var"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("Script.var Script.x1", x1Symbol.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x1).Symbol); VerifyModelForDeconstructionField(model, x1, x1Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Symbol = model.GetDeclaredSymbol(x3); var x3Ref = GetReference(tree, "x3"); Assert.Equal("Script.var Script.x3", x3Symbol.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x3).Symbol); VerifyModelForDeconstructionField(model, x3, x3Ref); // extra checks on x1's var var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("var", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(x1Type)); // extra checks on x3's var var x3Type = GetTypeSyntax(x3); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x3Type).Symbol.Kind); Assert.Equal("var", model.GetSymbolInfo(x3Type).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(x3Type)); } [Fact] public void SimpleDiscardWithConversion() { var source = @" class C { static void Main() { (int _, var x) = (new C(1), 1); (var _, var y) = (new C(2), 2); var (_, z) = (new C(3), 3); System.Console.Write($""Output {x} {y} {z}.""); } int _i; public C(int i) { _i = i; } public static implicit operator int(C c) { System.Console.Write($""Converted {c._i}. ""); return 0; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Converted 1. Output 1 2 3."); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetSymbolInfo(discard1).Symbol); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("int _", declaration1.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); var discard2 = GetDiscardDesignations(tree).ElementAt(1); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.Null(model.GetSymbolInfo(discard2).Symbol); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("var _", declaration2.ToString()); Assert.Equal("C", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); var discard3 = GetDiscardDesignations(tree).ElementAt(2); var declaration3 = (DeclarationExpressionSyntax)discard3.Parent.Parent; Assert.Equal("var (_, z)", declaration3.ToString()); Assert.Equal("(C, System.Int32 z)", model.GetTypeInfo(declaration3).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration3).Symbol); } [Fact] public void CannotDeconstructIntoDiscardOfWrongType() { var source = @" class C { static void Main() { (int _, string _) = (""hello"", 42); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,30): error CS0029: Cannot implicitly convert type 'string' to 'int' // (int _, string _) = ("hello", 42); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""hello""").WithArguments("string", "int").WithLocation(6, 30), // (6,39): error CS0029: Cannot implicitly convert type 'int' to 'string' // (int _, string _) = ("hello", 42); Diagnostic(ErrorCode.ERR_NoImplicitConv, "42").WithArguments("int", "string").WithLocation(6, 39) ); } [Fact] public void DiscardFromDeconstructMethod() { var source = @" class C { static void Main() { (var _, string y) = new C(); System.Console.Write(y); } void Deconstruct(out int x, out string y) { x = 42; y = ""hello""; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "hello"); } [Fact] public void ShortDiscardInDeclaration() { var source = @" class C { static void Main() { (_, var x) = (1, 2); System.Console.Write(x); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard = GetDiscardIdentifiers(tree).First(); var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol; Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal("System.Int32", model.GetTypeInfo(discard).Type.ToTestDisplayString()); var isymbol = (ISymbol)symbol; Assert.Equal(SymbolKind.Discard, isymbol.Kind); } [Fact, WorkItem(25829, "https://github.com/dotnet/roslyn/issues/25829")] public void SameTypeDiscardsAreEqual01() { var source = @" class C { static void Main() { (_, _) = (1, 2); _ = 3; M(out _); } static void M(out int x) => x = 1; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discards = GetDiscardIdentifiers(tree).ToArray(); Assert.Equal(4, discards.Length); var symbol0 = (IDiscardSymbol)model.GetSymbolInfo(discards[0]).Symbol; Assert.Equal(symbol0, symbol0); var set = new HashSet<ISymbol>(); foreach (var discard in discards) { var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol; set.Add(symbol); Assert.Equal(SymbolKind.Discard, symbol.Kind); Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal(symbol0, symbol); Assert.Equal(symbol, symbol); Assert.Equal(symbol.GetHashCode(), symbol0.GetHashCode()); // Test to show that reference-unequal discards are equal by type. IDiscardSymbol symbolClone = new DiscardSymbol(TypeWithAnnotations.Create(symbol.Type.GetSymbol())).GetPublicSymbol(); Assert.NotSame(symbol, symbolClone); Assert.Equal(SymbolKind.Discard, symbolClone.Kind); Assert.Equal("int _", symbolClone.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal(symbol.Type, symbolClone.Type); Assert.Equal(symbol0, symbolClone); Assert.Equal(symbol, symbolClone); Assert.Same(symbol.Type, symbolClone.Type); // original symbol for System.Int32 has identity. Assert.Equal(symbol.GetHashCode(), symbolClone.GetHashCode()); } Assert.Equal(1, set.Count); } [Fact, WorkItem(25829, "https://github.com/dotnet/roslyn/issues/25829")] public void SameTypeDiscardsAreEqual02() { var source = @"using System.Collections.Generic; class C { static void Main() { (_, _) = (new List<int>(), new List<int>()); _ = new List<int>(); M(out _); } static void M(out List<int> x) => x = new List<int>(); } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discards = GetDiscardIdentifiers(tree).ToArray(); Assert.Equal(4, discards.Length); var symbol0 = (IDiscardSymbol)model.GetSymbolInfo(discards[0]).Symbol; Assert.Equal(symbol0, symbol0); var set = new HashSet<ISymbol>(); foreach (var discard in discards) { var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol; set.Add(symbol); Assert.Equal(SymbolKind.Discard, symbol.Kind); Assert.Equal("List<int> _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal(symbol0, symbol); Assert.Equal(symbol0.Type, symbol.Type); Assert.Equal(symbol, symbol); Assert.Equal(symbol.GetHashCode(), symbol0.GetHashCode()); if (discard != discards[0]) { // Although it is not part of the compiler's contract, at the moment distinct constructions are distinct Assert.NotSame(symbol.Type, symbol0.Type); Assert.NotSame(symbol, symbol0); } } Assert.Equal(1, set.Count); } [Fact, WorkItem(25829, "https://github.com/dotnet/roslyn/issues/25829")] public void DifferentTypeDiscardsAreNotEqual() { var source = @" class C { static void Main() { (_, _) = (1.0, 2); _ = 3; M(out _); } static void M(out int x) => x = 1; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discards = GetDiscardIdentifiers(tree).ToArray(); Assert.Equal(4, discards.Length); var symbol0 = (IDiscardSymbol)model.GetSymbolInfo(discards[0]).Symbol; var set = new HashSet<ISymbol>(); foreach (var discard in discards) { var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol; Assert.Equal(SymbolKind.Discard, symbol.Kind); set.Add(symbol); if (discard == discards[0]) { Assert.Equal("double _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal(symbol0, symbol); Assert.Equal(symbol0.GetHashCode(), symbol.GetHashCode()); } else { Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.NotEqual(symbol0, symbol); } } Assert.Equal(2, set.Count); } [Fact] public void EscapedUnderscoreInDeclaration() { var source = @" class C { static void Main() { (@_, var x) = (1, 2); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,10): error CS0103: The name '_' does not exist in the current context // (@_, var x) = (1, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "@_").WithArguments("_").WithLocation(6, 10) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); Assert.Empty(GetDiscardIdentifiers(tree)); } [Fact] public void EscapedUnderscoreInDeclarationCSharp9() { var source = @" class C { static void Main() { (@_, var x) = (1, 2); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (@_, var x) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(@_, var x) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(6, 9), // (6,10): error CS0103: The name '_' does not exist in the current context // (@_, var x) = (1, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "@_").WithArguments("_").WithLocation(6, 10) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); Assert.Empty(GetDiscardIdentifiers(tree)); } [Fact] public void UnderscoreLocalInDeconstructDeclaration() { var source = @" class C { static void Main() { int _; (_, var x) = (1, 2); System.Console.Write(_); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1") .VerifyIL("C.Main", @" { // Code size 13 (0xd) .maxstack 1 .locals init (int V_0, //_ int V_1) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: call ""void System.Console.Write(int)"" IL_000b: nop IL_000c: ret }"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard = GetDiscardIdentifiers(tree).First(); Assert.Equal("(_, var x)", discard.Parent.Parent.ToString()); var symbol = (ILocalSymbol)model.GetSymbolInfo(discard).Symbol; Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal("System.Int32", model.GetTypeInfo(discard).Type.ToTestDisplayString()); } [Fact] public void ShortDiscardInDeconstructAssignment() { var source = @" class C { static void Main() { int x; (_, _, x) = (1, 2, 3); System.Console.Write(x); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void DiscardInDeconstructAssignment() { var source = @" class C { static void Main() { int x; (_, x) = (1L, 2); System.Console.Write(x); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardIdentifiers(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Equal("long _", model.GetSymbolInfo(discard1).Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); var tuple1 = (TupleExpressionSyntax)discard1.Parent.Parent; Assert.Equal("(_, x)", tuple1.ToString()); Assert.Equal("(System.Int64, System.Int32 x)", model.GetTypeInfo(tuple1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(tuple1).Symbol); } [Fact] public void DiscardInDeconstructDeclaration() { var source = @" class C { static void Main() { var (_, x) = (1, 2); System.Console.Write(x); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); var tuple1 = (DeclarationExpressionSyntax)discard1.Parent.Parent; Assert.Equal("var (_, x)", tuple1.ToString()); Assert.Equal("(System.Int32, System.Int32 x)", model.GetTypeInfo(tuple1).Type.ToTestDisplayString()); } [Fact] public void UnderscoreLocalInDeconstructAssignment() { var source = @" class C { static void Main() { int x, _; (_, x) = (1, 2); System.Console.Write($""{_} {x}""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1 2"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard = GetDiscardIdentifiers(tree).First(); Assert.Equal("(_, x)", discard.Parent.Parent.ToString()); var symbol = (ILocalSymbol)model.GetSymbolInfo(discard).Symbol; Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } [Fact] public void DiscardInForeach() { var source = @" class C { static void Main() { foreach (var (_, x) in new[] { (1, ""hello"") }) { System.Console.Write(""1 ""); } foreach ((_, (var y, int z)) in new[] { (1, (""hello"", 2)) }) { System.Console.Write(""2""); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1 2"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); DiscardDesignationSyntax discard1 = GetDiscardDesignations(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetTypeInfo(discard1).Type); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent.Parent; Assert.Equal("var (_, x)", declaration1.ToString()); Assert.Null(model.GetTypeInfo(discard1).Type); Assert.Equal("(System.Int32, System.String x)", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); IdentifierNameSyntax discard2 = GetDiscardIdentifiers(tree).First(); Assert.Equal("(_, (var y, int z))", discard2.Parent.Parent.ToString()); Assert.Equal("int _", model.GetSymbolInfo(discard2).Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal("System.Int32", model.GetTypeInfo(discard2).Type.ToTestDisplayString()); var yz = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(2); Assert.Equal("(var y, int z)", yz.ToString()); Assert.Equal("(System.String y, System.Int32 z)", model.GetTypeInfo(yz).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(yz).Symbol); var y = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(1); Assert.Equal("var y", y.ToString()); Assert.Equal("System.String", model.GetTypeInfo(y).Type.ToTestDisplayString()); Assert.Equal("System.String y", model.GetSymbolInfo(y).Symbol.ToTestDisplayString()); } [Fact] public void TwoDiscardsInForeach() { var source = @" class C { static void Main() { foreach ((_, _) in new[] { (1, ""hello"") }) { System.Console.Write(""2""); } } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var refs = GetReferences(tree, "_"); Assert.Equal(2, refs.Count()); model.GetTypeInfo(refs.ElementAt(0)); // Assert.Equal("int", model.GetTypeInfo(refs.ElementAt(0)).Type.ToDisplayString()); model.GetTypeInfo(refs.ElementAt(1)); // Assert.Equal("string", model.GetTypeInfo(refs.ElementAt(1)).Type.ToDisplayString()); var tuple = (TupleExpressionSyntax)refs.ElementAt(0).Parent.Parent; Assert.Equal("(_, _)", tuple.ToString()); Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(tuple).Type.ToTestDisplayString()); }; var comp = CompileAndVerify(source, expectedOutput: @"2", sourceSymbolValidator: validator); comp.VerifyDiagnostics( // this is permitted now, as it is just an assignment expression ); } [Fact] public void UnderscoreLocalDisallowedInForEach() { var source = @" class C { static void Main() { { foreach ((var x, _) in new[] { (1, ""hello"") }) { System.Console.Write(""2 ""); } } { int _; foreach ((var y, _) in new[] { (1, ""hello"") }) { System.Console.Write(""4""); } // error } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (11,30): error CS0029: Cannot implicitly convert type 'string' to 'int' // foreach ((var y, _) in new[] { (1, "hello") }) { System.Console.Write("4"); } // error Diagnostic(ErrorCode.ERR_NoImplicitConv, "_").WithArguments("string", "int").WithLocation(11, 30), // (11,22): error CS8186: A foreach loop must declare its iteration variables. // foreach ((var y, _) in new[] { (1, "hello") }) { System.Console.Write("4"); } // error Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(var y, _)").WithLocation(11, 22), // (10,17): warning CS0168: The variable '_' is declared but never used // int _; Diagnostic(ErrorCode.WRN_UnreferencedVar, "_").WithArguments("_").WithLocation(10, 17) ); } [Fact] public void TwoDiscardsInDeconstructAssignment() { var source = @" class C { static void Main() { (_, _) = (new C(), new C()); } public C() { System.Console.Write(""C""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "CC"); } [Fact] public void VerifyDiscardIL() { var source = @" class C { C() { System.Console.Write(""ctor""); } static int Main() { var (x, _, _) = (1, new C(), 2); return x; } } "; var comp = CompileAndVerify(source, expectedOutput: "ctor"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main()", @" { // Code size 8 (0x8) .maxstack 1 IL_0000: newobj ""C..ctor()"" IL_0005: pop IL_0006: ldc.i4.1 IL_0007: ret }"); } [Fact] public void SingleDiscardInAssignment() { var source = @" class C { static void Main() { _ = M(); } public static int M() { System.Console.Write(""M""); return 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "M"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardIdentifiers(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Equal("System.Int32", model.GetTypeInfo(discard1).Type.ToTestDisplayString()); } [Fact] public void SingleDiscardInAssignmentInCSharp6() { var source = @" class C { static void Error() { _ = 1; } static void Ok() { int _; _ = 1; System.Console.Write(_); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular6); comp.VerifyDiagnostics( // (6,9): error CS8059: Feature 'discards' is not available in C# 6. Please use language version 7.0 or greater. // _ = 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("discards", "7.0").WithLocation(6, 9) ); } [Fact] public void VariousDiscardsInCSharp6() { var source = @" class C { static void M1(out int x) { (_, var _, int _) = (1, 2, 3); var (_, _) = (1, 2); bool b = 3 is int _; switch (3) { case int _: break; } M1(out var _); M1(out int _); M1(out _); x = 2; } static void M2() { const int _ = 3; switch (3) { case _: // not a discard break; } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular6); comp.VerifyDiagnostics( // (6,9): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // (_, var _, int _) = (1, 2, 3); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(_, var _, int _)").WithArguments("tuples", "7.0").WithLocation(6, 9), // (6,10): error CS8059: Feature 'discards' is not available in C# 6. Please use language version 7.0 or greater. // (_, var _, int _) = (1, 2, 3); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("discards", "7.0").WithLocation(6, 10), // (6,29): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // (_, var _, int _) = (1, 2, 3); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(1, 2, 3)").WithArguments("tuples", "7.0").WithLocation(6, 29), // (7,13): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // var (_, _) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(_, _)").WithArguments("tuples", "7.0").WithLocation(7, 13), // (7,22): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // var (_, _) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(1, 2)").WithArguments("tuples", "7.0").WithLocation(7, 22), // (8,18): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // bool b = 3 is int _; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "3 is int _").WithArguments("pattern matching", "7.0").WithLocation(8, 18), // (11,13): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // case int _: Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "case int _:").WithArguments("pattern matching", "7.0").WithLocation(11, 13), // (14,20): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater. // M1(out var _); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("out variable declaration", "7.0").WithLocation(14, 20), // (15,20): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater. // M1(out int _); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("out variable declaration", "7.0").WithLocation(15, 20), // (16,16): error CS8059: Feature 'discards' is not available in C# 6. Please use language version 7.0 or greater. // M1(out _); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("discards", "7.0").WithLocation(16, 16), // (24,18): warning CS8512: The name '_' refers to the constant, not the discard pattern. Use 'var _' to discard the value, or '@_' to refer to a constant by that name. // case _: // not a discard Diagnostic(ErrorCode.WRN_CaseConstantNamedUnderscore, "_").WithLocation(24, 18) ); } [Fact] public void SingleDiscardInAsyncAssignment() { var source = @" class C { async void M() { System.Threading.Tasks.Task.Delay(new System.TimeSpan(0)); // warning _ = System.Threading.Tasks.Task.Delay(new System.TimeSpan(0)); // fire-and-forget await System.Threading.Tasks.Task.Delay(new System.TimeSpan(0)); } } "; var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (6,9): warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call. // System.Threading.Tasks.Task.Delay(new System.TimeSpan(0)); Diagnostic(ErrorCode.WRN_UnobservedAwaitableExpression, "System.Threading.Tasks.Task.Delay(new System.TimeSpan(0))").WithLocation(6, 9) ); } [Fact] public void SingleDiscardInUntypedAssignment() { var source = @" class C { static void Main() { _ = null; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,9): error CS8183: Cannot infer the type of implicitly-typed discard. // _ = null; Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(6, 9) ); } [Fact] public void UnderscoreLocalInAssignment() { var source = @" class C { static void Main() { int _; _ = M(); System.Console.Write(_); } public static int M() { return 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1"); } [Fact] public void DeclareAndUseLocalInDeconstruction() { var source = @" class C { static void Main() { (var x, x) = (1, 2); (y, var y) = (1, 2); } } "; var compCSharp9 = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compCSharp9.VerifyDiagnostics( // (6,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (var x, x) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(var x, x) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(6, 9), // (6,17): error CS0841: Cannot use local variable 'x' before it is declared // (var x, x) = (1, 2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 17), // (7,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (y, var y) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(y, var y) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(7, 9), // (7,10): error CS0841: Cannot use local variable 'y' before it is declared // (y, var y) = (1, 2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y").WithLocation(7, 10) ); var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (6,17): error CS0841: Cannot use local variable 'x' before it is declared // (var x, x) = (1, 2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 17), // (7,10): error CS0841: Cannot use local variable 'y' before it is declared // (y, var y) = (1, 2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y").WithLocation(7, 10) ); } [Fact] public void OutVarAndUsageInDeconstructAssignment() { var source = @" class C { static void Main() { (M(out var x).P, x) = (1, x); System.Console.Write(x); } static C M(out int i) { i = 42; return new C(); } int P { set { System.Console.Write($""Written {value}. ""); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,26): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (M(out var x).P, x) = (1, x); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(6, 26) ); CompileAndVerify(comp, expectedOutput: "Written 1. 42"); } [Fact] public void OutDiscardInDeconstructAssignment() { var source = @" class C { static void Main() { int _; (M(out var _).P, _) = (1, 2); System.Console.Write(_); } static C M(out int i) { i = 42; return new C(); } int P { set { System.Console.Write($""Written {value}. ""); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Written 1. 2"); } [Fact] public void OutDiscardInDeconstructTarget() { var source = @" class C { static void Main() { (x, _) = (M(out var x), 2); System.Console.Write(x); } static int M(out int i) { i = 42; return 3; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,10): error CS0841: Cannot use local variable 'x' before it is declared // (x, _) = (M(out var x), 2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 10) ); } [Fact] public void SimpleDiscardDeconstructInScript() { var source = @" using alias = System.Int32; (string _, alias _) = (""hello"", 42); "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).First(); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("string _", declaration1.ToString()); Assert.Null(model.GetDeclaredSymbol(declaration1)); Assert.Null(model.GetDeclaredSymbol(discard1)); var discard2 = GetDiscardDesignations(tree).ElementAt(1); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("alias _", declaration2.ToString()); Assert.Null(model.GetDeclaredSymbol(declaration2)); Assert.Null(model.GetDeclaredSymbol(discard2)); var tuple = (TupleExpressionSyntax)declaration1.Parent.Parent; Assert.Equal("(string _, alias _)", tuple.ToString()); Assert.Equal("(System.String, System.Int32)", model.GetTypeInfo(tuple).Type.ToTestDisplayString()); }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, sourceSymbolValidator: validator); } [Fact] public void SimpleDiscardDeconstructInScript2() { var source = @" public class C { public C() { System.Console.Write(""ctor""); } public void Deconstruct(out string x, out string y) { x = y = null; } } (string _, string _) = new C(); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "ctor"); } [Fact] public void SingleDiscardInAssignmentInScript() { var source = @" int M() { System.Console.Write(""M""); return 1; } _ = M(); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "M"); } [Fact] public void NestedVarDiscardDeconstructionInScript() { var source = @" (var _, var (_, x3)) = (""hello"", (42, 43)); System.Console.Write($""{x3}""); "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var discard2 = GetDiscardDesignations(tree).ElementAt(1); var nestedDeclaration = (DeclarationExpressionSyntax)discard2.Parent.Parent; Assert.Equal("var (_, x3)", nestedDeclaration.ToString()); Assert.Null(model.GetDeclaredSymbol(nestedDeclaration)); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.Equal("(System.Int32, System.Int32 x3)", model.GetTypeInfo(nestedDeclaration).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(nestedDeclaration).Symbol); var tuple = (TupleExpressionSyntax)discard2.Parent.Parent.Parent.Parent; Assert.Equal("(var _, var (_, x3))", tuple.ToString()); Assert.Equal("(System.String, (System.Int32, System.Int32 x3))", model.GetTypeInfo(tuple).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(tuple).Symbol); }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "43", sourceSymbolValidator: validator); } [Fact] public void VariousDiscardsInForeach() { var source = @" class C { static void Main() { foreach ((var _, int _, _, var (_, _), int x) in new[] { (1L, 2, 3, (""hello"", 5), 6) }) { System.Console.Write(x); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "6"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.True(model.GetSymbolInfo(discard1).IsEmpty); Assert.Null(model.GetTypeInfo(discard1).Type); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("var _", declaration1.ToString()); Assert.Equal("System.Int64", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); var discard2 = GetDiscardDesignations(tree).ElementAt(1); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.True(model.GetSymbolInfo(discard2).IsEmpty); Assert.Null(model.GetTypeInfo(discard2).Type); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("int _", declaration2.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); var discard3 = GetDiscardIdentifiers(tree).First(); Assert.Equal("_", discard3.Parent.ToString()); Assert.Null(model.GetDeclaredSymbol(discard3)); Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString()); Assert.Equal("int _", model.GetSymbolInfo(discard3).Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol; Assert.Equal("System.Int32", discard3Symbol.Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString()); var discard4 = GetDiscardDesignations(tree).ElementAt(2); Assert.Null(model.GetDeclaredSymbol(discard4)); Assert.True(model.GetSymbolInfo(discard4).IsEmpty); Assert.Null(model.GetTypeInfo(discard4).Type); var nestedDeclaration = (DeclarationExpressionSyntax)discard4.Parent.Parent; Assert.Equal("var (_, _)", nestedDeclaration.ToString()); Assert.Equal("(System.String, System.Int32)", model.GetTypeInfo(nestedDeclaration).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(nestedDeclaration).Symbol); } [Fact] public void UnderscoreInCSharp6Foreach() { var source = @" class C { static void Main() { foreach (var _ in M()) { System.Console.Write(_); } } static System.Collections.Generic.IEnumerable<int> M() { System.Console.Write(""M ""); yield return 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "M 1"); } [Fact] public void ShortDiscardDisallowedInForeach() { var source = @" class C { static void Main() { foreach (_ in M()) { } } static System.Collections.Generic.IEnumerable<int> M() { yield return 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,18): error CS8186: A foreach loop must declare its iteration variables. // foreach (_ in M()) Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "_").WithLocation(6, 18) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var discard = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().First(); var symbol = (DiscardSymbol)model.GetSymbolInfo(discard).Symbol.GetSymbol(); Assert.True(symbol.TypeWithAnnotations.Type.IsErrorType()); } [Fact] public void ExistingUnderscoreLocalInLegacyForeach() { var source = @" class C { static void Main() { int _; foreach (var _ in new[] { 1 }) { } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,22): error CS0136: A local or parameter named '_' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var _ in new[] { 1 }) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "_").WithArguments("_").WithLocation(7, 22), // (6,13): warning CS0168: The variable '_' is declared but never used // int _; Diagnostic(ErrorCode.WRN_UnreferencedVar, "_").WithArguments("_").WithLocation(6, 13) ); } [Fact] public void MixedDeconstruction_01() { string source = @" class Program { static void Main(string[] args) { var t = (1, 2); var x = (int x1, int x2) = t; System.Console.WriteLine(x1); System.Console.WriteLine(x2); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (7,18): error CS8185: A declaration is not allowed in this context. // var x = (int x1, int x2) = t; Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(7, 18) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); } [Fact] public void MixedDeconstruction_02() { string source = @" class Program { static void Main(string[] args) { var t = (1, 2); int z; (int x1, z) = t; System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "1") .VerifyIL("Program.Main", @" { // Code size 32 (0x20) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0, //t int V_1, //z int V_2) //x1 IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000a: ldloc.0 IL_000b: dup IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0011: stloc.2 IL_0012: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0017: stloc.1 IL_0018: ldloc.2 IL_0019: call ""void System.Console.WriteLine(int)"" IL_001e: nop IL_001f: ret }"); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); } [Fact] public void MixedDeconstruction_03() { string source = @" class Program { static void Main(string[] args) { var t = (1, 2); int z; for ((int x1, z) = t; ; ) { System.Console.WriteLine(x1); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "1") .VerifyIL("Program.Main", @" { // Code size 39 (0x27) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0, //t int V_1, //z int V_2) //x1 IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000a: ldloc.0 IL_000b: dup IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0011: stloc.2 IL_0012: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0017: stloc.1 IL_0018: br.s IL_0024 IL_001a: nop IL_001b: ldloc.2 IL_001c: call ""void System.Console.WriteLine(int)"" IL_0021: nop IL_0022: br.s IL_0026 IL_0024: br.s IL_001a IL_0026: ret }"); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var symbolInfo = model.GetSymbolInfo(x1Ref); Assert.Equal(symbolInfo.Symbol, model.GetDeclaredSymbol(x1)); Assert.Equal(SpecialType.System_Int32, symbolInfo.Symbol.GetTypeOrReturnType().SpecialType); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(int x1, z)", lhs.ToString()); Assert.Equal("(System.Int32 x1, System.Int32 z)", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 x1, System.Int32 z)", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); } [Fact] public void MixedDeconstruction_03CSharp9() { string source = @" class Program { static void Main(string[] args) { var t = (1, 2); int z; for ((int x1, z) = t; ; ) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (8,14): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // for ((int x1, z) = t; ; ) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int x1, z) = t").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(8, 14)); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); } [Fact] public void MixedDeconstruction_04() { string source = @" class Program { static void Main(string[] args) { var t = (1, 2); for (; ; (int x1, int x2) = t) { System.Console.WriteLine(x1); System.Console.WriteLine(x2); } } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (7,19): error CS8185: A declaration is not allowed in this context. // for (; ; (int x1, int x2) = t) Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(7, 19), // (9,38): error CS0103: The name 'x1' does not exist in the current context // System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(9, 38), // (10,38): error CS0103: The name 'x2' does not exist in the current context // System.Console.WriteLine(x2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(10, 38) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1); var symbolInfo = model.GetSymbolInfo(x1Ref); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2); symbolInfo = model.GetSymbolInfo(x2Ref); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); } [Fact] public void MixedDeconstruction_05() { string source = @" class Program { static void Main(string[] args) { foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) }) { System.Console.WriteLine(x1); System.Console.WriteLine(x2); } } static int _M; static ref int M(out int x) { x = 2; return ref _M; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,34): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) }) Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "args is var x2").WithLocation(6, 34), // (6,34): error CS0029: Cannot implicitly convert type 'int' to 'bool' // foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) }) Diagnostic(ErrorCode.ERR_NoImplicitConv, "args is var x2").WithArguments("int", "bool").WithLocation(6, 34), // (6,18): error CS8186: A foreach loop must declare its iteration variables. // foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) }) Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(M(out var x1), args is var x2, _)").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.Equal("int", model.GetTypeInfo(x1Ref).Type.ToDisplayString()); model = compilation.GetSemanticModel(tree); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); Assert.Equal("string[]", model.GetTypeInfo(x2Ref).Type.ToDisplayString()); VerifyModelForLocal(model, x1, LocalDeclarationKind.OutVariable, x1Ref); VerifyModelForLocal(model, x2, LocalDeclarationKind.PatternVariable, x2Ref); } [Fact] public void ForeachIntoExpression() { string source = @" class Program { static void Main(string[] args) { foreach (M(out var x1) in new[] { 1, 2, 3 }) { System.Console.WriteLine(x1); } } static int _M; static ref int M(out int x) { x = 2; return ref _M; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,32): error CS0230: Type and identifier are both required in a foreach statement // foreach (M(out var x1) in new[] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(6, 32) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.Equal("int", model.GetTypeInfo(x1Ref).Type.ToDisplayString()); VerifyModelForLocal(model, x1, LocalDeclarationKind.OutVariable, x1Ref); } [Fact] public void MixedDeconstruction_06() { string source = @" class Program { static void Main(string[] args) { foreach (M1(M2(out var x1, args is var x2), x1, x2) in new[] {1, 2, 3}) { System.Console.WriteLine(x1); System.Console.WriteLine(x2); } } static int _M; static ref int M1(int m2, int x, string[] y) { return ref _M; } static int M2(out int x, bool b) => x = 2; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,61): error CS0230: Type and identifier are both required in a foreach statement // foreach (M1(M2(out var x1, args is var x2), x1, x2) in new[] {1, 2, 3}) Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(6, 61) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReferences(tree, "x1"); Assert.Equal("int", model.GetTypeInfo(x1Ref.First()).Type.ToDisplayString()); model = compilation.GetSemanticModel(tree); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReferences(tree, "x2"); Assert.Equal("string[]", model.GetTypeInfo(x2Ref.First()).Type.ToDisplayString()); VerifyModelForLocal(model, x1, LocalDeclarationKind.OutVariable, x1Ref.ToArray()); VerifyModelForLocal(model, x2, LocalDeclarationKind.PatternVariable, x2Ref.ToArray()); } [Fact] public void MixedDeconstruction_07() { string source = @" class Program { static void Main(string[] args) { var t = (1, ("""", true)); string y; for ((int x, (y, var z)) = t; ; ) { System.Console.Write(x); System.Console.Write(z); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation, expectedOutput: "1True") .VerifyIL("Program.Main", @" { // Code size 73 (0x49) .maxstack 4 .locals init (System.ValueTuple<int, System.ValueTuple<string, bool>> V_0, //t string V_1, //y int V_2, //x bool V_3, //z System.ValueTuple<string, bool> V_4) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldstr """" IL_0009: ldc.i4.1 IL_000a: newobj ""System.ValueTuple<string, bool>..ctor(string, bool)"" IL_000f: call ""System.ValueTuple<int, System.ValueTuple<string, bool>>..ctor(int, System.ValueTuple<string, bool>)"" IL_0014: ldloc.0 IL_0015: dup IL_0016: ldfld ""System.ValueTuple<string, bool> System.ValueTuple<int, System.ValueTuple<string, bool>>.Item2"" IL_001b: stloc.s V_4 IL_001d: ldfld ""int System.ValueTuple<int, System.ValueTuple<string, bool>>.Item1"" IL_0022: stloc.2 IL_0023: ldloc.s V_4 IL_0025: ldfld ""string System.ValueTuple<string, bool>.Item1"" IL_002a: stloc.1 IL_002b: ldloc.s V_4 IL_002d: ldfld ""bool System.ValueTuple<string, bool>.Item2"" IL_0032: stloc.3 IL_0033: br.s IL_0046 IL_0035: nop IL_0036: ldloc.2 IL_0037: call ""void System.Console.Write(int)"" IL_003c: nop IL_003d: ldloc.3 IL_003e: call ""void System.Console.Write(bool)"" IL_0043: nop IL_0044: br.s IL_0048 IL_0046: br.s IL_0035 IL_0048: ret }"); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xRef = GetReference(tree, "x"); VerifyModelForDeconstructionLocal(model, x, xRef); var xSymbolInfo = model.GetSymbolInfo(xRef); Assert.Equal(xSymbolInfo.Symbol, model.GetDeclaredSymbol(x)); Assert.Equal(SpecialType.System_Int32, xSymbolInfo.Symbol.GetTypeOrReturnType().SpecialType); var z = GetDeconstructionVariable(tree, "z"); var zRef = GetReference(tree, "z"); VerifyModelForDeconstructionLocal(model, z, zRef); var zSymbolInfo = model.GetSymbolInfo(zRef); Assert.Equal(zSymbolInfo.Symbol, model.GetDeclaredSymbol(z)); Assert.Equal(SpecialType.System_Boolean, zSymbolInfo.Symbol.GetTypeOrReturnType().SpecialType); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(2); Assert.Equal(@"(int x, (y, var z))", lhs.ToString()); Assert.Equal("(System.Int32 x, (System.String y, System.Boolean z))", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 x, (System.String y, System.Boolean z))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); } [Fact] public void IncompleteDeclarationIsSeenAsTupleLiteral() { string source = @" class C { static void Main() { (int x1, string x2); System.Console.WriteLine(x1); System.Console.WriteLine(x2); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,10): error CS8185: A declaration is not allowed in this context. // (int x1, string x2); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 10), // (6,18): error CS8185: A declaration is not allowed in this context. // (int x1, string x2); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "string x2").WithLocation(6, 18), // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (int x1, string x2); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x1, string x2)").WithLocation(6, 9), // (6,10): error CS0165: Use of unassigned local variable 'x1' // (int x1, string x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 10), // (6,18): error CS0165: Use of unassigned local variable 'x2' // (int x1, string x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "string x2").WithArguments("x2").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.Equal("int", model.GetTypeInfo(x1Ref).Type.ToDisplayString()); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); Assert.Equal("string", model.GetTypeInfo(x2Ref).Type.ToDisplayString()); VerifyModelForDeconstruction(model, x1, LocalDeclarationKind.DeclarationExpressionVariable, x1Ref); VerifyModelForDeconstruction(model, x2, LocalDeclarationKind.DeclarationExpressionVariable, x2Ref); } [Fact] [WorkItem(15893, "https://github.com/dotnet/roslyn/issues/15893")] public void DeconstructionOfOnlyOneElement() { string source = @" class C { static void Main() { var (p2) = (1, 2); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,16): error CS1003: Syntax error, ',' expected // var (p2) = (1, 2); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(",", ")").WithLocation(6, 16), // (6,16): error CS1001: Identifier expected // var (p2) = (1, 2); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(6, 16) ); } [Fact] [WorkItem(14876, "https://github.com/dotnet/roslyn/issues/14876")] public void TupleTypeInDeconstruction() { string source = @" class C { static void Main() { (int x, (string, long) y) = M(); System.Console.Write($""{x} {y}""); } static (int, (string, long)) M() { return (5, (""Goo"", 34983490)); } } "; var comp = CompileAndVerify(source, expectedOutput: "5 (Goo, 34983490)"); comp.VerifyDiagnostics(); } [Fact] [WorkItem(12468, "https://github.com/dotnet/roslyn/issues/12468")] public void RefReturningVarInvocation() { string source = @" class C { static int i; static void Main() { int x = 0, y = 0; (var(x, y)) = 42; // parsed as invocation System.Console.Write(i); } static ref int var(int a, int b) { return ref i; } } "; var comp = CompileAndVerify(source, expectedOutput: "42", verify: Verification.Passes); comp.VerifyDiagnostics(); } [Fact] void InvokeVarForLvalueInParens() { var source = @" class Program { public static void Main() { (var(x, y)) = 10; System.Console.WriteLine(z); } static int x = 1, y = 2, z = 3; static ref int var(int x, int y) { return ref z; } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); // PEVerify fails with ref return https://github.com/dotnet/roslyn/issues/12285 CompileAndVerify(compilation, expectedOutput: "10", verify: Verification.Fails); } [Fact] [WorkItem(16106, "https://github.com/dotnet/roslyn/issues/16106")] public void DefAssignmentsStruct001() { string source = @" using System.Collections.Generic; public class MyClass { public static void Main() { ((int, int), string)[] arr = new((int, int), string)[1]; Test5(arr); } public static void Test4(IEnumerable<(KeyValuePair<int, int>, string)> en) { foreach ((KeyValuePair<int, int> kv, string s) in en) { var a = kv.Key; // false error CS0170: Use of possibly unassigned field } } public static void Test5(IEnumerable<((int, int), string)> en) { foreach (((int, int k) t, string s) in en) { var a = t.k; // false error CS0170: Use of possibly unassigned field System.Console.WriteLine(a); } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "0"); } [Fact] [WorkItem(16106, "https://github.com/dotnet/roslyn/issues/16106")] public void DefAssignmentsStruct002() { string source = @" public class MyClass { public static void Main() { var data = new int[10]; var arr = new int[2]; foreach (arr[out int size] in data) {} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,36): error CS0230: Type and identifier are both required in a foreach statement // foreach (arr[out int size] in data) {} Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(9, 36) ); } [Fact] [WorkItem(16106, "https://github.com/dotnet/roslyn/issues/16106")] public void DefAssignmentsStruct003() { string source = @" public class MyClass { public static void Main() { var data = new (int, int)[10]; var arr = new int[2]; foreach ((arr[out int size], int b) in data) {} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,27): error CS1615: Argument 1 may not be passed with the 'out' keyword // foreach ((arr[out int size], int b) in data) {} Diagnostic(ErrorCode.ERR_BadArgExtraRef, "int size").WithArguments("1", "out").WithLocation(9, 27), // (9,18): error CS8186: A foreach loop must declare its iteration variables. // foreach ((arr[out int size], int b) in data) {} Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(arr[out int size], int b)").WithLocation(9, 18) ); } [Fact] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_01() { string source = @" class C { static event System.Action E; static void Main() { (E, _) = (null, 1); System.Console.WriteLine(E == null); (E, _) = (Handler, 1); E(); } static void Handler() { System.Console.WriteLine(""Handler""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"True Handler"); comp.VerifyDiagnostics(); } [Fact] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_02() { string source = @" struct S { event System.Action E; class C { static void Main() { var s = new S(); (s.E, _) = (null, 1); System.Console.WriteLine(s.E == null); (s.E, _) = (Handler, 1); s.E(); } static void Handler() { System.Console.WriteLine(""Handler""); } } } "; var comp = CompileAndVerify(source, expectedOutput: @"True Handler"); comp.VerifyDiagnostics(); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.WinRTNeedsWindowsDesktop)] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_03() { string source1 = @" public interface EventInterface { event System.Action E; } "; var comp1 = CreateEmptyCompilation(source1, WinRtRefs, TestOptions.ReleaseWinMD, TestOptions.Regular); string source2 = @" class C : EventInterface { public event System.Action E; static void Main() { var c = new C(); c.Test(); } void Test() { (E, _) = (null, 1); System.Console.WriteLine(E == null); (E, _) = (Handler, 1); E(); } static void Handler() { System.Console.WriteLine(""Handler""); } } "; var comp2 = CompileAndVerify(source2, targetFramework: TargetFramework.Empty, expectedOutput: @"True Handler", references: WinRtRefs.Concat(new[] { ValueTupleRef, comp1.ToMetadataReference() })); comp2.VerifyDiagnostics(); Assert.True(comp2.Compilation.GetMember<IEventSymbol>("C.E").IsWindowsRuntimeEvent); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.WinRTNeedsWindowsDesktop)] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_04() { string source1 = @" public interface EventInterface { event System.Action E; } "; var comp1 = CreateEmptyCompilation(source1, WinRtRefs, TestOptions.ReleaseWinMD, TestOptions.Regular); string source2 = @" struct S : EventInterface { public event System.Action E; class C { S s = new S(); static void Main() { var c = new C(); (GetC(c).s.E, _) = (null, GetInt(1)); System.Console.WriteLine(c.s.E == null); (GetC(c).s.E, _) = (Handler, GetInt(2)); c.s.E(); } static int GetInt(int i) { System.Console.WriteLine(i); return i; } static C GetC(C c) { System.Console.WriteLine(""GetC""); return c; } static void Handler() { System.Console.WriteLine(""Handler""); } } } "; var comp2 = CompileAndVerify(source2, targetFramework: TargetFramework.Empty, expectedOutput: @"GetC 1 True GetC 2 Handler", references: WinRtRefs.Concat(new[] { ValueTupleRef, comp1.ToMetadataReference() })); comp2.VerifyDiagnostics(); Assert.True(comp2.Compilation.GetMember<IEventSymbol>("S.E").IsWindowsRuntimeEvent); } [Fact] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_05() { string source = @" class C { public static event System.Action E; } class Program { static void Main() { (C.E, _) = (null, 1); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,12): error CS0070: The event 'C.E' can only appear on the left hand side of += or -= (except when used from within the type 'C') // (C.E, _) = (null, 1); Diagnostic(ErrorCode.ERR_BadEventUsage, "E").WithArguments("C.E", "C").WithLocation(11, 12) ); } [Fact] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_06() { string source = @" class C { static event System.Action E { add {} remove {} } static void Main() { (E, _) = (null, 1); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (12,10): error CS0079: The event 'C.E' can only appear on the left hand side of += or -= // (E, _) = (null, 1); Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "E").WithArguments("C.E").WithLocation(12, 10) ); } [Fact] public void SimpleAssignInConstructor() { string source = @" public class C { public long x; public string y; public C(int a, string b) => (x, y) = (a, b); public static void Main() { var c = new C(1, ""hello""); System.Console.WriteLine(c.x + "" "" + c.y); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C..ctor(int, string)", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (long V_0, string V_1) IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.1 IL_0007: conv.i8 IL_0008: stloc.0 IL_0009: ldarg.2 IL_000a: stloc.1 IL_000b: ldarg.0 IL_000c: ldloc.0 IL_000d: stfld ""long C.x"" IL_0012: ldarg.0 IL_0013: ldloc.1 IL_0014: stfld ""string C.y"" IL_0019: ret }"); } [Fact] public void DeconstructAssignInConstructor() { string source = @" public class C { public long x; public string y; public C(C oldC) => (x, y) = oldC; public C() { } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } public static void Main() { var oldC = new C() { x = 1, y = ""hello"" }; var newC = new C(oldC); System.Console.WriteLine(newC.x + "" "" + newC.y); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C..ctor(C)", @" { // Code size 34 (0x22) .maxstack 3 .locals init (int V_0, string V_1, long V_2) IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.1 IL_0007: ldloca.s V_0 IL_0009: ldloca.s V_1 IL_000b: callvirt ""void C.Deconstruct(out int, out string)"" IL_0010: ldloc.0 IL_0011: conv.i8 IL_0012: stloc.2 IL_0013: ldarg.0 IL_0014: ldloc.2 IL_0015: stfld ""long C.x"" IL_001a: ldarg.0 IL_001b: ldloc.1 IL_001c: stfld ""string C.y"" IL_0021: ret }"); } [Fact] public void AssignInConstructorWithProperties() { string source = @" public class C { public long X { get; set; } public string Y { get; } private int z; public ref int Z { get { return ref z; } } public C(int a, string b, ref int c) => (X, Y, Z) = (a, b, c); public static void Main() { int number = 2; var c = new C(1, ""hello"", ref number); System.Console.WriteLine($""{c.X} {c.Y} {c.Z}""); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello 2"); comp.VerifyDiagnostics(); comp.VerifyIL("C..ctor(int, string, ref int)", @" { // Code size 39 (0x27) .maxstack 4 .locals init (long V_0, string V_1, int V_2, long V_3) IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: call ""ref int C.Z.get"" IL_000c: ldarg.1 IL_000d: conv.i8 IL_000e: stloc.0 IL_000f: ldarg.2 IL_0010: stloc.1 IL_0011: ldarg.3 IL_0012: ldind.i4 IL_0013: stloc.2 IL_0014: ldarg.0 IL_0015: ldloc.0 IL_0016: dup IL_0017: stloc.3 IL_0018: call ""void C.X.set"" IL_001d: ldarg.0 IL_001e: ldloc.1 IL_001f: stfld ""string C.<Y>k__BackingField"" IL_0024: ldloc.2 IL_0025: stind.i4 IL_0026: ret }"); } [Fact] public void VerifyDeconstructionInAsync() { var source = @" using System.Threading.Tasks; class C { static void Main() { System.Console.Write(C.M().Result); } static async Task<int> M() { await Task.Delay(0); var (x, y) = (1, 2); return x + y; } } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void DeconstructionWarnsForSelfAssignment() { var source = @" class C { object x = 1; static object y = 2; void M() { ((x, x), this.x, C.y) = ((x, (1, 2)), x, y); } } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,11): warning CS1717: Assignment made to same variable; did you mean to assign something else? // ((x, x), this.x, C.y) = ((x, (1, 2)), x, y); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(8, 11), // (8,18): warning CS1717: Assignment made to same variable; did you mean to assign something else? // ((x, x), this.x, C.y) = ((x, (1, 2)), x, y); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "this.x").WithLocation(8, 18), // (8,26): warning CS1717: Assignment made to same variable; did you mean to assign something else? // ((x, x), this.x, C.y) = ((x, (1, 2)), x, y); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "C.y").WithLocation(8, 26) ); } [Fact] public void DeconstructionWarnsForSelfAssignment2() { var source = @" class C { object x = 1; static object y = 2; void M() { object z = 3; (x, (y, z)) = (x, (y, z)); } } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (9,10): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (x, (y, z)) = (x, (y, z)); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x"), // (9,14): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (x, (y, z)) = (x, (y, z)); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "y").WithLocation(9, 14), // (9,17): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (x, (y, z)) = (x, (y, z)); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "z").WithLocation(9, 17) ); } [Fact] public void DeconstructionWarnsForSelfAssignment_WithUserDefinedConversionOnElement() { var source = @" class C { object x = 1; static C y = null; void M() { (x, y) = (x, (C)(D)y); } public static implicit operator C(D d) => null; } class D { public static implicit operator D(C c) => null; } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,10): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (x, y) = (x, (C)(D)y); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(8, 10) ); } [Fact] public void DeconstructionWarnsForSelfAssignment_WithNestedConversions() { var source = @" class C { object x = 1; int y = 2; byte b = 3; void M() { // The conversions on the right-hand-side: // - a deconstruction conversion // - an implicit tuple literal conversion on the entire right-hand-side // - another implicit tuple literal conversion on the nested tuple // - a conversion on element `b` (_, (x, y)) = (1, (x, b)); } } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (14,14): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (_, (x, y)) = (1, (x, b)); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(14, 14) ); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DeconstructionWarnsForSelfAssignment_WithExplicitTupleConversion() { var source = @" class C { int y = 2; byte b = 3; void M() { // The conversions on the right-hand-side: // - a deconstruction conversion on the entire right-hand-side // - an identity conversion as its operand // - an explicit tuple literal conversion as its operand (y, _) = ((int, int))(y, b); } } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( ); var tree = comp.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); Assert.Equal("((int, int))(y, b)", node.ToString()); comp.VerifyOperationTree(node, expectedOperationTree: @" IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32)) (Syntax: '((int, int))(y, b)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Int32 y, System.Int32 b)) (Syntax: '(y, b)') NaturalType: (System.Int32 y, System.Byte b) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.Int32 C.y (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'y') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.Byte C.b (OperationKind.FieldReference, Type: System.Byte) (Syntax: 'b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'b') "); } [Fact] public void DeconstructionWarnsForSelfAssignment_WithDeconstruct() { var source = @" class C { object x = 1; static object y = 2; void M() { object z = 3; (x, (y, z)) = (x, y); } } static class Extensions { public static void Deconstruct(this object input, out object output1, out object output2) { output1 = input; output2 = input; } }"; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (9,10): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (x, (y, z)) = (x, y); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(9, 10) ); } [Fact] public void TestDeconstructOnErrorType() { var source = @" class C { Error M() { int x, y; (x, y) = M(); throw null; } }"; var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll); // no ValueTuple reference comp.VerifyDiagnostics( // (4,5): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // Error M() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 5) ); } [Fact] public void TestDeconstructOnErrorTypeFromImageReference() { var missing_cs = "public class Missing { }"; var missing = CreateCompilationWithMscorlib45(missing_cs, options: TestOptions.DebugDll, assemblyName: "missing"); var lib_cs = "public class C { public Missing M() { throw null; } }"; var lib = CreateCompilationWithMscorlib45(lib_cs, references: new[] { missing.EmitToImageReference() }, options: TestOptions.DebugDll); var source = @" class D { void M() { int x, y; (x, y) = new C().M(); throw null; } }"; var comp = CreateCompilationWithMscorlib45(source, references: new[] { lib.EmitToImageReference() }, options: TestOptions.DebugDll); // no ValueTuple reference comp.VerifyDiagnostics( // (7,18): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (x, y) = new C().M(); Diagnostic(ErrorCode.ERR_NoTypeDef, "new C().M").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18) ); } [Fact] public void TestDeconstructOnErrorTypeFromCompilationReference() { var missing_cs = "public class Missing { }"; var missing = CreateCompilationWithMscorlib45(missing_cs, options: TestOptions.DebugDll, assemblyName: "missing"); var lib_cs = "public class C { public Missing M() { throw null; } }"; var lib = CreateCompilationWithMscorlib45(lib_cs, references: new[] { missing.ToMetadataReference() }, options: TestOptions.DebugDll); var source = @" class D { void M() { int x, y; (x, y) = new C().M(); throw null; } }"; var comp = CreateCompilationWithMscorlib45(source, references: new[] { lib.ToMetadataReference() }, options: TestOptions.DebugDll); // no ValueTuple reference comp.VerifyDiagnostics( // (7,18): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (x, y) = new C().M(); Diagnostic(ErrorCode.ERR_NoTypeDef, "new C().M").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18) ); } [Fact, WorkItem(17756, "https://github.com/dotnet/roslyn/issues/17756")] public void TestDiscardedAssignmentNotLvalue() { var source = @" class Program { struct S1 { public int field; public int Increment() => field++; } static void Main() { S1 v = default(S1); v.Increment(); (_ = v).Increment(); System.Console.WriteLine(v.field); } } "; string expectedOutput = @"1"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void TupleCastInDeconstruction() { var source = @" class C { static void Main() { var t = (1, 2); var (a, b) = ((byte, byte))t; System.Console.Write($""{a} {b}""); } }"; CompileAndVerify(source, expectedOutput: @"1 2"); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void TupleCastInDeconstruction2() { var source = @" class C { static void Main() { var t = (new C(), new D()); var (a, _) = ((byte, byte))t; System.Console.Write($""{a}""); } public static explicit operator byte(C c) { System.Console.Write(""Convert ""); return 1; } } class D { public static explicit operator byte(D c) { System.Console.Write(""Convert2 ""); return 2; } }"; CompileAndVerify(source, expectedOutput: @"Convert Convert2 1"); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void TupleCastInDeconstruction3() { var source = @" class C { static int A { set { System.Console.Write(""A ""); } } static int B { set { System.Console.Write(""B""); } } static void Main() { (A, B) = ((byte, byte))(new C(), new D()); } public static explicit operator byte(C c) { System.Console.Write(""Convert ""); return 1; } public C() { System.Console.Write(""C ""); } } class D { public static explicit operator byte(D c) { System.Console.Write(""Convert2 ""); return 2; } public D() { System.Console.Write(""D ""); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"C Convert D Convert2 A B").Compilation; var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); Assert.Equal("((byte, byte))(new C(), new D())", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Byte, System.Byte)) (Syntax: '((byte, byt ... ), new D())') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Byte, System.Byte)) (Syntax: '(new C(), new D())') NaturalType: (C, D) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Byte C.op_Explicit(C c)) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 'new C()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Byte C.op_Explicit(C c)) Operand: IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Byte D.op_Explicit(D c)) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 'new D()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Byte D.op_Explicit(D c)) Operand: IObjectCreationOperation (Constructor: D..ctor()) (OperationKind.ObjectCreation, Type: D) (Syntax: 'new D()') Arguments(0) Initializer: null "); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void TupleCastInDeconstruction4() { var source = @" class C { static void Main() { var (a, _) = ((short, short))((int, int))(1L, 2L); System.Console.Write($""{a}""); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1").Compilation; var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().ElementAt(1); Assert.Equal("((int, int))(1L, 2L)", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32)) (Syntax: '((int, int))(1L, 2L)') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1L, 2L)') NaturalType: (System.Int64, System.Int64) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1L') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 1) (Syntax: '1L') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2L') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 2) (Syntax: '2L') "); Assert.Equal("((short, short))((int, int))(1L, 2L)", node.Parent.ToString()); compilation.VerifyOperationTree(node.Parent, expectedOperationTree: @" IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int16, System.Int16)) (Syntax: '((short, sh ... t))(1L, 2L)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32)) (Syntax: '((int, int))(1L, 2L)') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1L, 2L)') NaturalType: (System.Int64, System.Int64) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1L') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 1) (Syntax: '1L') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2L') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 2) (Syntax: '2L') "); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void UserDefinedCastInDeconstruction() { var source = @" class C { static void Main() { var c = new C(); var (a, b) = ((byte, byte))c; System.Console.Write($""{a} {b}""); } public static explicit operator (byte, byte)(C c) { return (3, 4); } }"; CompileAndVerify(source, expectedOutput: @"3 4"); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void DeconstructionLoweredToNothing() { var source = @" class C { static void M() { for (var(_, _) = (1, 2); ; (_, _) = (3, 4)) { } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp); verifier.VerifyIL("C.M", @" { // Code size 2 (0x2) .maxstack 0 IL_0000: br.s IL_0000 }"); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void DeconstructionLoweredToNothing2() { var source = @" class C { static void M() { (_, _) = (1, 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp); verifier.VerifyIL("C.M", @" { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void DeconstructionLoweredToNothing3() { var source = @" class C { static void Main() { foreach (var(_, _) in new[] { (1, 2) }) { System.Console.Write(""once""); } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "once"); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact] public void InferredName() { var source = @"class C { static void Main() { int x = 0, y = 1; var t = (x, y); var (a, b) = t; } }"; // C# 7.0 var comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(); // C# 7.1 comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact] public void InferredName_ConditionalOperator() { var source = @"class C { static void M(int a, int b, bool c) { (var x, var y) = c ? (a, default(object)) : (b, null); (x, y) = c ? (a, default(string)) : (b, default(object)); } }"; // C# 7.0 var comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(); // C# 7.1 comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact] public void InferredName_ImplicitArray() { var source = @"class C { static void M(int x) { int y; object z; (y, z) = (new [] { (x, default(object)), (2, 3) })[0]; } }"; // C# 7.0 var comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(); // C# 7.1 comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/32006")] public void InferredName_Lambda() { // See https://github.com/dotnet/roslyn/issues/32006 // need to relax assertion in GetImplicitTupleLiteralConversion var source = @"class C { static T F<T>(System.Func<object, bool, T> f) { return f(null, false); } static void M() { var (x, y) = F((a, b) => { if (b) return (default(object), a); return (null, null); }); } }"; // C# 7.0 var comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(); // C# 7.1 comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact] public void InferredName_ConditionalOperator_LongTuple() { var source = @"class C { static void M(object a, object b, bool c) { var (_1, _2, _3, _4, _5, _6, _7, _8, _9, _10) = c ? (1, 2, 3, 4, 5, 6, 7, a, b, 10) : (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); } }"; // C# 7.0 var comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(); // C# 7.1 comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact] public void InferredName_ConditionalOperator_UseSite() { var source = @"class C { static void M(int a, int b, bool c) { var (x, y) = c ? ((object)1, a) : (b, 2); } } namespace System { struct ValueTuple<T1, T2> { public T1 Item1; private T2 Item2; public ValueTuple(T1 item1, T2 item2) => throw null; } }"; var expected = new[] { // (12,19): warning CS0649: Field '(T1, T2).Item1' is never assigned to, and will always have its default value // public T1 Item1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Item1").WithArguments("(T1, T2).Item1", "").WithLocation(12, 19), // (13,20): warning CS0169: The field '(T1, T2).Item2' is never used // private T2 Item2; Diagnostic(ErrorCode.WRN_UnreferencedField, "Item2").WithArguments("(T1, T2).Item2").WithLocation(13, 20) }; // C# 7.0 var comp = CreateCompilation( source, assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08", parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(expected); // C# 7.1 comp = CreateCompilation( source, assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08", parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(expected); } [Fact] public void InferredName_ConditionalOperator_UseSite_AccessingWithinConstructor() { var source = @"class C { static void M(int a, int b, bool c) { var (x, y) = c ? ((object)1, a) : (b, 2); } } namespace System { struct ValueTuple<T1, T2> { public T1 Item1; private T2 Item2; public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } } }"; var expected = new[] { // (13,20): warning CS0169: The field '(T1, T2).Item2' is never used // private T2 Item2; Diagnostic(ErrorCode.WRN_UnreferencedField, "Item2").WithArguments("(T1, T2).Item2").WithLocation(13, 20), // (14,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(14, 16), // (14,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(14, 16), // (17,13): error CS0229: Ambiguity between '(T1, T2).Item2' and '(T1, T2).Item2' // Item2 = item2; Diagnostic(ErrorCode.ERR_AmbigMember, "Item2").WithArguments("(T1, T2).Item2", "(T1, T2).Item2").WithLocation(17, 13) }; // C# 7.0 var comp = CreateCompilation( source, assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08", parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(expected); // C# 7.1 comp = CreateCompilation( source, assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08", parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(expected); } [Fact] public void TestGetDeconstructionInfoOnIncompleteCode() { string source = @" class C { void M() { var (y1, y2) =} void Deconstruct(out int x1, out int x2) { x1 = 1; x2 = 2; } } "; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First(); Assert.Equal("var (y1, y2) =", node.ToString()); var info = model.GetDeconstructionInfo(node); Assert.Null(info.Method); Assert.Empty(info.Nested); } [Fact] public void TestDeconstructStructThis() { string source = @" public struct S { int I; public static void Main() { S s = new S(); s.M(); } public void M() { this.I = 42; var (x, (y, z)) = (this, this /* mutating deconstruction */); System.Console.Write($""{x.I} {y} {z}""); } void Deconstruct(out int x1, out int x2) { x1 = I++; x2 = I++; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "42 42 43"); } [Fact] public void TestDeconstructClassThis() { string source = @" public class C { int I; public static void Main() { C c = new C(); c.M(); } public void M() { this.I = 42; var (x, (y, z)) = (this, this /* mutating deconstruction */); System.Console.Write($""{x.I} {y} {z}""); } void Deconstruct(out int x1, out int x2) { x1 = I++; x2 = I++; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "44 42 43"); } [Fact] public void AssigningConditional_OutParams() { string source = @" using System; class C { static void Main() { Test(true, false); Test(false, true); Test(false, false); } static void Test(bool b1, bool b2) { M(out int x, out int y, b1, b2); Console.Write(x); Console.Write(y); } static void M(out int x, out int y, bool b1, bool b2) { (x, y) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60); } } "; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "102030405060"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @" { // Code size 33 (0x21) .maxstack 2 IL_0000: ldarg.2 IL_0001: brtrue.s IL_0018 IL_0003: ldarg.3 IL_0004: brtrue.s IL_000f IL_0006: ldarg.0 IL_0007: ldc.i4.s 50 IL_0009: stind.i4 IL_000a: ldarg.1 IL_000b: ldc.i4.s 60 IL_000d: stind.i4 IL_000e: ret IL_000f: ldarg.0 IL_0010: ldc.i4.s 30 IL_0012: stind.i4 IL_0013: ldarg.1 IL_0014: ldc.i4.s 40 IL_0016: stind.i4 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.s 10 IL_001b: stind.i4 IL_001c: ldarg.1 IL_001d: ldc.i4.s 20 IL_001f: stind.i4 IL_0020: ret }"); } [Fact] public void AssigningConditional_VarDeconstruction() { string source = @" using System; class C { static void Main() { M(true, false); M(false, true); M(false, false); } static void M(bool b1, bool b2) { var (x, y) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60); Console.Write(x); Console.Write(y); } } "; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "102030405060"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @" { // Code size 41 (0x29) .maxstack 1 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: brtrue.s IL_0016 IL_0003: ldarg.1 IL_0004: brtrue.s IL_000e IL_0006: ldc.i4.s 50 IL_0008: stloc.0 IL_0009: ldc.i4.s 60 IL_000b: stloc.1 IL_000c: br.s IL_001c IL_000e: ldc.i4.s 30 IL_0010: stloc.0 IL_0011: ldc.i4.s 40 IL_0013: stloc.1 IL_0014: br.s IL_001c IL_0016: ldc.i4.s 10 IL_0018: stloc.0 IL_0019: ldc.i4.s 20 IL_001b: stloc.1 IL_001c: ldloc.0 IL_001d: call ""void System.Console.Write(int)"" IL_0022: ldloc.1 IL_0023: call ""void System.Console.Write(int)"" IL_0028: ret }"); } [Fact] public void AssigningConditional_MixedDeconstruction() { string source = @" using System; class C { static void Main() { M(true, false); M(false, true); M(false, false); } static void M(bool b1, bool b2) { (var x, long y) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60); Console.Write(x); Console.Write(y); } } "; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "102030405060"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @" { // Code size 50 (0x32) .maxstack 1 .locals init (int V_0, //x long V_1, //y long V_2) IL_0000: ldarg.0 IL_0001: brtrue.s IL_001c IL_0003: ldarg.1 IL_0004: brtrue.s IL_0011 IL_0006: ldc.i4.s 60 IL_0008: conv.i8 IL_0009: stloc.2 IL_000a: ldc.i4.s 50 IL_000c: stloc.0 IL_000d: ldloc.2 IL_000e: stloc.1 IL_000f: br.s IL_0025 IL_0011: ldc.i4.s 40 IL_0013: conv.i8 IL_0014: stloc.2 IL_0015: ldc.i4.s 30 IL_0017: stloc.0 IL_0018: ldloc.2 IL_0019: stloc.1 IL_001a: br.s IL_0025 IL_001c: ldc.i4.s 20 IL_001e: conv.i8 IL_001f: stloc.2 IL_0020: ldc.i4.s 10 IL_0022: stloc.0 IL_0023: ldloc.2 IL_0024: stloc.1 IL_0025: ldloc.0 IL_0026: call ""void System.Console.Write(int)"" IL_002b: ldloc.1 IL_002c: call ""void System.Console.Write(long)"" IL_0031: ret }"); } [Fact] public void AssigningConditional_SideEffects() { string source = @" using System; class C { static void Main() { M(true, false); M(false, true); M(false, false); SideEffect(true); SideEffect(false); } static int left; static int right; static ref int SideEffect(bool isLeft) { Console.WriteLine($""{(isLeft ? ""left"" : ""right"")}: {(isLeft ? left : right)}""); return ref isLeft ? ref left : ref right; } static void M(bool b1, bool b2) { (SideEffect(isLeft: true), SideEffect(isLeft: false)) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60); } } "; var expected = @"left: 0 right: 0 left: 10 right: 20 left: 30 right: 40 left: 50 right: 60"; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expected); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (int& V_0, int& V_1) IL_0000: ldc.i4.1 IL_0001: call ""ref int C.SideEffect(bool)"" IL_0006: stloc.0 IL_0007: ldc.i4.0 IL_0008: call ""ref int C.SideEffect(bool)"" IL_000d: stloc.1 IL_000e: ldarg.0 IL_000f: brtrue.s IL_0026 IL_0011: ldarg.1 IL_0012: brtrue.s IL_001d IL_0014: ldloc.0 IL_0015: ldc.i4.s 50 IL_0017: stind.i4 IL_0018: ldloc.1 IL_0019: ldc.i4.s 60 IL_001b: stind.i4 IL_001c: ret IL_001d: ldloc.0 IL_001e: ldc.i4.s 30 IL_0020: stind.i4 IL_0021: ldloc.1 IL_0022: ldc.i4.s 40 IL_0024: stind.i4 IL_0025: ret IL_0026: ldloc.0 IL_0027: ldc.i4.s 10 IL_0029: stind.i4 IL_002a: ldloc.1 IL_002b: ldc.i4.s 20 IL_002d: stind.i4 IL_002e: ret }"); } [Fact] public void AssigningConditional_SideEffects_RHS() { string source = @" using System; class C { static void Main() { M(true, false); M(false, true); M(false, false); } static T Echo<T>(T v, int i) { Console.WriteLine(i + "": "" + v); return v; } static void M(bool b1, bool b2) { var (x, y) = Echo(b1, 1) ? Echo((10, 20), 2) : Echo(b2, 3) ? Echo((30, 40), 4) : Echo((50, 60), 5); Console.WriteLine(""x: "" + x); Console.WriteLine(""y: "" + y); Console.WriteLine(); } } "; var expectedOutput = @"1: True 2: (10, 20) x: 10 y: 20 1: False 3: True 4: (30, 40) x: 30 y: 40 1: False 3: False 5: (50, 60) x: 50 y: 60 "; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); comp.VerifyDiagnostics(); } [Fact] public void AssigningConditional_UnusedDeconstruction() { string source = @" class C { static void M(bool b1, bool b2) { (_, _) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60); } } "; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldarg.1 IL_0004: pop IL_0005: ret }"); } [Fact, WorkItem(46562, "https://github.com/dotnet/roslyn/issues/46562")] public void CompoundAssignment() { string source = @" class C { void M() { decimal x = 0; (var y, _) += 0.00m; (int z, _) += z; (var t, _) += (1, 2); } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,17): warning CS0219: The variable 'x' is assigned but its value is never used // decimal x = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 17), // (7,10): error CS8185: A declaration is not allowed in this context. // (var y, _) += 0.00m; Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var y").WithLocation(7, 10), // (7,17): error CS0103: The name '_' does not exist in the current context // (var y, _) += 0.00m; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(7, 17), // (8,10): error CS8185: A declaration is not allowed in this context. // (int z, _) += z; Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int z").WithLocation(8, 10), // (8,10): error CS0165: Use of unassigned local variable 'z' // (int z, _) += z; Diagnostic(ErrorCode.ERR_UseDefViolation, "int z").WithArguments("z").WithLocation(8, 10), // (8,17): error CS0103: The name '_' does not exist in the current context // (int z, _) += z; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(8, 17), // (9,10): error CS8185: A declaration is not allowed in this context. // (var t, _) += (1, 2); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var t").WithLocation(9, 10), // (9,17): error CS0103: The name '_' does not exist in the current context // (var t, _) += (1, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(9, 17) ); } [Fact, WorkItem(50654, "https://github.com/dotnet/roslyn/issues/50654")] public void Repro50654() { string source = @" class C { static void Main() { (int, (int, (int, int), (int, int)))[] vals = new[] { (1, (2, (3, 4), (5, 6))), (11, (12, (13, 14), (15, 16))) }; foreach (var (a, (b, (c, d), (e, f))) in vals) { System.Console.Write($""{a + b + c + d + e + f} ""); } foreach ((int a, (int b, (int c, int d), (int e, int f))) in vals) { System.Console.Write($""{a + b + c + d + e + f} ""); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "21 81 21 81"); } [Fact] public void MixDeclarationAndAssignmentPermutationsOf2() { string source = @" class C { static void Main() { int x1 = 0; (x1, string y1) = new C(); System.Console.WriteLine(x1 + "" "" + y1); int x2; (x2, var y2) = new C(); System.Console.WriteLine(x2 + "" "" + y2); string y3 = """"; (int x3, y3) = new C(); System.Console.WriteLine(x3 + "" "" + y3); string y4; (var x4, y4) = new C(); System.Console.WriteLine(x4 + "" "" + y4); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello 1 hello 1 hello 1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 188 (0xbc) .maxstack 3 .locals init (int V_0, //x1 string V_1, //y1 int V_2, //x2 string V_3, //y2 string V_4, //y3 int V_5, //x3 string V_6, //y4 int V_7, //x4 int V_8, string V_9) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: newobj ""C..ctor()"" IL_0007: ldloca.s V_8 IL_0009: ldloca.s V_9 IL_000b: callvirt ""void C.Deconstruct(out int, out string)"" IL_0010: ldloc.s V_8 IL_0012: stloc.0 IL_0013: ldloc.s V_9 IL_0015: stloc.1 IL_0016: ldloca.s V_0 IL_0018: call ""string int.ToString()"" IL_001d: ldstr "" "" IL_0022: ldloc.1 IL_0023: call ""string string.Concat(string, string, string)"" IL_0028: call ""void System.Console.WriteLine(string)"" IL_002d: newobj ""C..ctor()"" IL_0032: ldloca.s V_8 IL_0034: ldloca.s V_9 IL_0036: callvirt ""void C.Deconstruct(out int, out string)"" IL_003b: ldloc.s V_8 IL_003d: stloc.2 IL_003e: ldloc.s V_9 IL_0040: stloc.3 IL_0041: ldloca.s V_2 IL_0043: call ""string int.ToString()"" IL_0048: ldstr "" "" IL_004d: ldloc.3 IL_004e: call ""string string.Concat(string, string, string)"" IL_0053: call ""void System.Console.WriteLine(string)"" IL_0058: ldstr """" IL_005d: stloc.s V_4 IL_005f: newobj ""C..ctor()"" IL_0064: ldloca.s V_8 IL_0066: ldloca.s V_9 IL_0068: callvirt ""void C.Deconstruct(out int, out string)"" IL_006d: ldloc.s V_8 IL_006f: stloc.s V_5 IL_0071: ldloc.s V_9 IL_0073: stloc.s V_4 IL_0075: ldloca.s V_5 IL_0077: call ""string int.ToString()"" IL_007c: ldstr "" "" IL_0081: ldloc.s V_4 IL_0083: call ""string string.Concat(string, string, string)"" IL_0088: call ""void System.Console.WriteLine(string)"" IL_008d: newobj ""C..ctor()"" IL_0092: ldloca.s V_8 IL_0094: ldloca.s V_9 IL_0096: callvirt ""void C.Deconstruct(out int, out string)"" IL_009b: ldloc.s V_8 IL_009d: stloc.s V_7 IL_009f: ldloc.s V_9 IL_00a1: stloc.s V_6 IL_00a3: ldloca.s V_7 IL_00a5: call ""string int.ToString()"" IL_00aa: ldstr "" "" IL_00af: ldloc.s V_6 IL_00b1: call ""string string.Concat(string, string, string)"" IL_00b6: call ""void System.Console.WriteLine(string)"" IL_00bb: ret }"); } [Fact] public void MixDeclarationAndAssignmentPermutationsOf3() { string source = @" class C { static void Main() { int x1; string y1; (x1, y1, var z1) = new C(); System.Console.WriteLine(x1 + "" "" + y1 + "" "" + z1); int x2; bool z2; (x2, var y2, z2) = new C(); System.Console.WriteLine(x2 + "" "" + y2 + "" "" + z2); string y3; bool z3; (var x3, y3, z3) = new C(); System.Console.WriteLine(x3 + "" "" + y3 + "" "" + z3); bool z4; (var x4, var y4, z4) = new C(); System.Console.WriteLine(x4 + "" "" + y4 + "" "" + z4); string y5; (var x5, y5, var z5) = new C(); System.Console.WriteLine(x5 + "" "" + y5 + "" "" + z5); int x6; (x6, var y6, var z6) = new C(); System.Console.WriteLine(x6 + "" "" + y6 + "" "" + z6); } public void Deconstruct(out int a, out string b, out bool c) { a = 1; b = ""hello""; c = true; } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello True 1 hello True 1 hello True 1 hello True 1 hello True 1 hello True"); comp.VerifyDiagnostics(); } [Fact] public void DontAllowMixedDeclarationAndAssignmentInExpressionContext() { string source = @" class C { static void Main() { int x1 = 0; var z1 = (x1, string y1) = new C(); string y2 = """"; var z2 = (int x2, y2) = new C(); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; CreateCompilation(source).VerifyDiagnostics( // (7,23): error CS8185: A declaration is not allowed in this context. // var z1 = (x1, string y1) = new C(); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "string y1").WithLocation(7, 23), // (9,19): error CS8185: A declaration is not allowed in this context. // var z2 = (int x2, y2) = new C(); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x2").WithLocation(9, 19)); } [Fact] public void DontAllowMixedDeclarationAndAssignmentInForeachDeclarationVariable() { string source = @" class C { static void Main() { int x1; foreach((x1, string y1) in new C[0]); string y2; foreach((int x2, y2) in new C[0]); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; CreateCompilation(source).VerifyDiagnostics( // (6,13): warning CS0168: The variable 'x1' is declared but never used // int x1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(6, 13), // (7,17): error CS8186: A foreach loop must declare its iteration variables. // foreach((x1, string y1) in new C[0]); Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(x1, string y1)").WithLocation(7, 17), // (8,16): warning CS0168: The variable 'y2' is declared but never used // string y2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "y2").WithArguments("y2").WithLocation(8, 16), // (9,17): error CS8186: A foreach loop must declare its iteration variables. // foreach((int x2, y2) in new C[0]); Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(int x2, y2)").WithLocation(9, 17)); } [Fact] public void DuplicateDeclarationOfVariableDeclaredInMixedDeclarationAndAssignment() { string source = @" class C { static void Main() { int x1; string y1; (x1, string y1) = new C(); string y2; (int x2, y2) = new C(); int x2; } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; CreateCompilation(source, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (7,16): warning CS0168: The variable 'y1' is declared but never used // string y1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "y1").WithArguments("y1").WithLocation(7, 16), // (8,21): error CS0128: A local variable or function named 'y1' is already defined in this scope // (x1, string y1) = new C(); Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(8, 21), // (11,13): error CS0128: A local variable or function named 'x2' is already defined in this scope // int x2; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(11, 13), // (11,13): warning CS0168: The variable 'x2' is declared but never used // int x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(11, 13)); } [Fact] public void AssignmentToUndeclaredVariableInMixedDeclarationAndAssignment() { string source = @" class C { static void Main() { (x1, string y1) = new C(); (int x2, y2) = new C(); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; CreateCompilation(source, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (6,10): error CS0103: The name 'x1' does not exist in the current context // (x1, string y1) = new C(); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 10), // (7,18): error CS0103: The name 'y2' does not exist in the current context // (int x2, y2) = new C(); Diagnostic(ErrorCode.ERR_NameNotInContext, "y2").WithArguments("y2").WithLocation(7, 18)); } [Fact] public void MixedDeclarationAndAssignmentInForInitialization() { string source = @" class C { static void Main() { int x1; for((x1, string y1) = new C(); x1 < 2; x1++) System.Console.WriteLine(x1 + "" "" + y1); string y2; for((int x2, y2) = new C(); x2 < 2; x2++) System.Console.WriteLine(x2 + "" "" + y2); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello 1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 109 (0x6d) .maxstack 3 .locals init (int V_0, //x1 string V_1, //y2 string V_2, //y1 int V_3, string V_4, int V_5) //x2 IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_3 IL_0007: ldloca.s V_4 IL_0009: callvirt ""void C.Deconstruct(out int, out string)"" IL_000e: ldloc.3 IL_000f: stloc.0 IL_0010: ldloc.s V_4 IL_0012: stloc.2 IL_0013: br.s IL_0030 IL_0015: ldloca.s V_0 IL_0017: call ""string int.ToString()"" IL_001c: ldstr "" "" IL_0021: ldloc.2 IL_0022: call ""string string.Concat(string, string, string)"" IL_0027: call ""void System.Console.WriteLine(string)"" IL_002c: ldloc.0 IL_002d: ldc.i4.1 IL_002e: add IL_002f: stloc.0 IL_0030: ldloc.0 IL_0031: ldc.i4.2 IL_0032: blt.s IL_0015 IL_0034: newobj ""C..ctor()"" IL_0039: ldloca.s V_3 IL_003b: ldloca.s V_4 IL_003d: callvirt ""void C.Deconstruct(out int, out string)"" IL_0042: ldloc.3 IL_0043: stloc.s V_5 IL_0045: ldloc.s V_4 IL_0047: stloc.1 IL_0048: br.s IL_0067 IL_004a: ldloca.s V_5 IL_004c: call ""string int.ToString()"" IL_0051: ldstr "" "" IL_0056: ldloc.1 IL_0057: call ""string string.Concat(string, string, string)"" IL_005c: call ""void System.Console.WriteLine(string)"" IL_0061: ldloc.s V_5 IL_0063: ldc.i4.1 IL_0064: add IL_0065: stloc.s V_5 IL_0067: ldloc.s V_5 IL_0069: ldc.i4.2 IL_006a: blt.s IL_004a IL_006c: ret }"); } [Fact] public void MixDeclarationAndAssignmentInTupleDeconstructPermutationsOf2() { string source = @" class C { static void Main() { int x1 = 0; (x1, string y1) = (1, ""hello""); System.Console.WriteLine(x1 + "" "" + y1); int x2; (x2, var y2) = (1, ""hello""); System.Console.WriteLine(x2 + "" "" + y2); string y3 = """"; (int x3, y3) = (1, ""hello""); System.Console.WriteLine(x3 + "" "" + y3); string y4; (var x4, y4) = (1, ""hello""); System.Console.WriteLine(x4 + "" "" + y4); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello 1 hello 1 hello 1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 140 (0x8c) .maxstack 3 .locals init (int V_0, //x1 string V_1, //y1 int V_2, //x2 string V_3, //y2 string V_4, //y3 int V_5, //x3 string V_6, //y4 int V_7) //x4 IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldc.i4.1 IL_0003: stloc.0 IL_0004: ldstr ""hello"" IL_0009: stloc.1 IL_000a: ldloca.s V_0 IL_000c: call ""string int.ToString()"" IL_0011: ldstr "" "" IL_0016: ldloc.1 IL_0017: call ""string string.Concat(string, string, string)"" IL_001c: call ""void System.Console.WriteLine(string)"" IL_0021: ldc.i4.1 IL_0022: stloc.2 IL_0023: ldstr ""hello"" IL_0028: stloc.3 IL_0029: ldloca.s V_2 IL_002b: call ""string int.ToString()"" IL_0030: ldstr "" "" IL_0035: ldloc.3 IL_0036: call ""string string.Concat(string, string, string)"" IL_003b: call ""void System.Console.WriteLine(string)"" IL_0040: ldstr """" IL_0045: stloc.s V_4 IL_0047: ldc.i4.1 IL_0048: stloc.s V_5 IL_004a: ldstr ""hello"" IL_004f: stloc.s V_4 IL_0051: ldloca.s V_5 IL_0053: call ""string int.ToString()"" IL_0058: ldstr "" "" IL_005d: ldloc.s V_4 IL_005f: call ""string string.Concat(string, string, string)"" IL_0064: call ""void System.Console.WriteLine(string)"" IL_0069: ldc.i4.1 IL_006a: stloc.s V_7 IL_006c: ldstr ""hello"" IL_0071: stloc.s V_6 IL_0073: ldloca.s V_7 IL_0075: call ""string int.ToString()"" IL_007a: ldstr "" "" IL_007f: ldloc.s V_6 IL_0081: call ""string string.Concat(string, string, string)"" IL_0086: call ""void System.Console.WriteLine(string)"" IL_008b: ret }"); } [Fact] public void MixedDeclarationAndAssignmentCSharpNine() { string source = @" class Program { static void Main() { int x1; (x1, string y1) = new A(); string y2; (int x2, y2) = new A(); bool z3; (int x3, (string y3, z3)) = new B(); int x4; (x4, var (y4, z4)) = new B(); } } class A { public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } class B { public void Deconstruct(out int a, out (string b, bool c) tuple) { a = 1; tuple = (""hello"", true); } } "; CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (7,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (x1, string y1) = new A(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(x1, string y1) = new A()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(7, 9), // (9,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (int x2, y2) = new A(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int x2, y2) = new A()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(9, 9), // (11,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (int x3, (string y3, z3)) = new B(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int x3, (string y3, z3)) = new B()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(11, 9), // (13,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (x4, var (y4, z4)) = new B(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(x4, var (y4, z4)) = new B()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(13, 9)); } [Fact] public void NestedMixedDeclarationAndAssignmentPermutations() { string source = @" class C { static void Main() { int x1; string y1; (x1, (y1, var z1)) = new C(); System.Console.WriteLine(x1 + "" "" + y1 + "" "" + z1); int x2; bool z2; (x2, (var y2, z2)) = new C(); System.Console.WriteLine(x2 + "" "" + y2 + "" "" + z2); string y3; bool z3; (var x3, (y3, z3)) = new C(); System.Console.WriteLine(x3 + "" "" + y3 + "" "" + z3); bool z4; (var x4, (var y4, z4)) = new C(); System.Console.WriteLine(x4 + "" "" + y4 + "" "" + z4); string y5; (var x5, (y5, var z5)) = new C(); System.Console.WriteLine(x5 + "" "" + y5 + "" "" + z5); int x6; (x6, (var y6, var z6)) = new C(); System.Console.WriteLine(x6 + "" "" + y6 + "" "" + z6); int x7; (x7, var (y7, z7)) = new C(); System.Console.WriteLine(x7 + "" "" + y7 + "" "" + z7); } public void Deconstruct(out int a, out (string a, bool b) b) { a = 1; b = (""hello"", true); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello True 1 hello True 1 hello True 1 hello True 1 hello True 1 hello True 1 hello True"); comp.VerifyDiagnostics(); } [Fact] public void MixedDeclarationAndAssignmentUseBeforeDeclaration() { string source = @" class Program { static void Main() { (x1, string y1) = new A(); int x1; (int x2, y2) = new A(); string y2; (int x3, (string y3, z3)) = new B(); bool z3; (x4, var (y4, z4)) = new B(); int x4; } } class A { public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } class B { public void Deconstruct(out int a, out (string b, bool c) tuple) { a = 1; tuple = (""hello"", true); } } "; CreateCompilation(source, parseOptions: TestOptions.RegularPreview) .VerifyDiagnostics( // (6,10): error CS0841: Cannot use local variable 'x1' before it is declared // (x1, string y1) = new A(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1", isSuppressed: false).WithArguments("x1").WithLocation(6, 10), // (8,18): error CS0841: Cannot use local variable 'y2' before it is declared // (int x2, y2) = new A(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y2", isSuppressed: false).WithArguments("y2").WithLocation(8, 18), // (10,30): error CS0841: Cannot use local variable 'z3' before it is declared // (int x3, (string y3, z3)) = new B(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "z3", isSuppressed: false).WithArguments("z3").WithLocation(10, 30), // (12,10): error CS0841: Cannot use local variable 'x4' before it is declared // (x4, var (y4, z4)) = new B(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4", isSuppressed: false).WithArguments("x4").WithLocation(12, 10)); } [Fact] public void MixedDeclarationAndAssignmentUseDeclaredVariableInAssignment() { string source = @" class Program { static void Main() { (var x1, x1) = new A(); (x2, var x2) = new A(); (var x3, (var y3, x3)) = new B(); (x4, (var y4, var x4)) = new B(); } } class A { public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } class B { public void Deconstruct(out int a, out (string b, bool c) tuple) { a = 1; tuple = (""hello"", true); } } "; CreateCompilation(source, parseOptions: TestOptions.RegularPreview) .VerifyDiagnostics( // (6,18): error CS0841: Cannot use local variable 'x1' before it is declared // (var x1, x1) = new A(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 18), // (7,10): error CS0841: Cannot use local variable 'x2' before it is declared // (x2, var x2) = new A(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(7, 10), // (8,27): error CS0841: Cannot use local variable 'x3' before it is declared // (var x3, (var y3, x3)) = new B(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x3").WithArguments("x3").WithLocation(8, 27), // (9,10): error CS0841: Cannot use local variable 'x4' before it is declared // (x4, (var y4, var x4)) = new B(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 10)); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { [CompilerTrait(CompilerFeature.Tuples)] public class CodeGenDeconstructTests : CSharpTestBase { private static readonly MetadataReference[] s_valueTupleRefs = new[] { SystemRuntimeFacadeRef, ValueTupleRef }; const string commonSource = @"public class Pair<T1, T2> { T1 item1; T2 item2; public Pair(T1 item1, T2 item2) { this.item1 = item1; this.item2 = item2; } public void Deconstruct(out T1 item1, out T2 item2) { System.Console.WriteLine($""Deconstructing {ToString()}""); item1 = this.item1; item2 = this.item2; } public override string ToString() { return $""({item1.ToString()}, {item2.ToString()})""; } } public static class Pair { public static Pair<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Pair<T1, T2>(item1, item2); } } public class Integer { public int state; public override string ToString() { return state.ToString(); } public Integer(int i) { state = i; } public static implicit operator LongInteger(Integer i) { System.Console.WriteLine($""Converting {i}""); return new LongInteger(i.state); } } public class LongInteger { long state; public LongInteger(long l) { state = l; } public override string ToString() { return state.ToString(); } }"; [Fact] public void SimpleAssign() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(x, y)", lhs.ToString()); Assert.Equal("(System.Int64 x, System.String y)", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int64 x, System.String y)", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); var right = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single(); Assert.Equal(@"new C()", right.ToString()); Assert.Equal("C", model.GetTypeInfo(right).Type.ToTestDisplayString()); Assert.Equal("C", model.GetTypeInfo(right).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(right).Kind); }; var comp = CompileAndVerifyWithMscorlib40(source, expectedOutput: "1 hello", references: s_valueTupleRefs, sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 43 (0x2b) .maxstack 3 .locals init (long V_0, //x string V_1, //y int V_2, string V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_2 IL_0007: ldloca.s V_3 IL_0009: callvirt ""void C.Deconstruct(out int, out string)"" IL_000e: ldloc.2 IL_000f: conv.i8 IL_0010: stloc.0 IL_0011: ldloc.3 IL_0012: stloc.1 IL_0013: ldloca.s V_0 IL_0015: call ""string long.ToString()"" IL_001a: ldstr "" "" IL_001f: ldloc.1 IL_0020: call ""string string.Concat(string, string, string)"" IL_0025: call ""void System.Console.WriteLine(string)"" IL_002a: ret }"); } [Fact] public void ObsoleteDeconstructMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); foreach (var (z1, z2) in new[] { new C() }) { } } [System.Obsolete] public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,18): warning CS0612: 'C.Deconstruct(out int, out string)' is obsolete // (x, y) = new C(); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "new C()").WithArguments("C.Deconstruct(out int, out string)").WithLocation(9, 18), // (10,34): warning CS0612: 'C.Deconstruct(out int, out string)' is obsolete // foreach (var (z1, z2) in new[] { new C() }) { } Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "new[] { new C() }").WithArguments("C.Deconstruct(out int, out string)").WithLocation(10, 34) ); } [Fact] [WorkItem(13632, "https://github.com/dotnet/roslyn/issues/13632")] public void SimpleAssignWithoutConversion() { string source = @" class C { static void Main() { int x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 42 (0x2a) .maxstack 3 .locals init (int V_0, //x string V_1, //y int V_2, string V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_2 IL_0007: ldloca.s V_3 IL_0009: callvirt ""void C.Deconstruct(out int, out string)"" IL_000e: ldloc.2 IL_000f: stloc.0 IL_0010: ldloc.3 IL_0011: stloc.1 IL_0012: ldloca.s V_0 IL_0014: call ""string int.ToString()"" IL_0019: ldstr "" "" IL_001e: ldloc.1 IL_001f: call ""string string.Concat(string, string, string)"" IL_0024: call ""void System.Console.WriteLine(string)"" IL_0029: ret }"); } [Fact] public void DeconstructMethodAmbiguous() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } public void Deconstruct(out int a) { a = 2; } }"; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); var deconstruction = (AssignmentExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.SimpleAssignmentExpression).AsNode(); Assert.Equal("(x, y) = new C()", deconstruction.ToString()); var deconstructionInfo = model.GetDeconstructionInfo(deconstruction); var firstDeconstructMethod = ((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("C").GetMembers(WellKnownMemberNames.DeconstructMethodName) .OfType<SourceOrdinaryMethodSymbol>().Where(m => m.ParameterCount == 2).Single(); Assert.Equal(firstDeconstructMethod.GetPublicSymbol(), deconstructionInfo.Method); Assert.Equal("void C.Deconstruct(out System.Int32 a, out System.String b)", deconstructionInfo.Method.ToTestDisplayString()); Assert.Null(deconstructionInfo.Conversion); var nested = deconstructionInfo.Nested; Assert.Equal(2, nested.Length); Assert.Null(nested[0].Method); Assert.Equal(ConversionKind.ImplicitNumeric, nested[0].Conversion.Value.Kind); Assert.Empty(nested[0].Nested); Assert.Null(nested[1].Method); Assert.Equal(ConversionKind.Identity, nested[1].Conversion.Value.Kind); Assert.Empty(nested[1].Nested); var assignment = (AssignmentExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.SimpleAssignmentExpression, occurrence: 2).AsNode(); Assert.Equal("a = 1", assignment.ToString()); var defaultInfo = model.GetDeconstructionInfo(assignment); Assert.Null(defaultInfo.Method); Assert.Empty(defaultInfo.Nested); Assert.Equal(ConversionKind.UnsetConversionKind, defaultInfo.Conversion.Value.Kind); } [Fact] [WorkItem(27520, "https://github.com/dotnet/roslyn/issues/27520")] public void GetDeconstructionInfoOnIncompleteCode() { string source = @" class C { static void M(string s) { foreach (char in s) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS1525: Invalid expression term 'char' // foreach (char in s) { } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "char").WithArguments("char").WithLocation(6, 18), // (6,23): error CS0230: Type and identifier are both required in a foreach statement // foreach (char in s) { } Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(6, 23) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var foreachDeconstruction = (ForEachVariableStatementSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.ForEachVariableStatement).AsNode(); Assert.Equal(@"foreach (char in s) { }", foreachDeconstruction.ToString()); var deconstructionInfo = model.GetDeconstructionInfo(foreachDeconstruction); Assert.Equal(Conversion.UnsetConversion, deconstructionInfo.Conversion); Assert.Null(deconstructionInfo.Method); Assert.Empty(deconstructionInfo.Nested); } [Fact] [WorkItem(15634, "https://github.com/dotnet/roslyn/issues/15634")] public void DeconstructMustReturnVoid() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); } public int Deconstruct(out int a, out string b) { a = 1; b = ""hello""; return 42; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS8129: No Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type. // (x, y) = new C(); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 18) ); } [Fact] public void VerifyExecutionOrder_Deconstruct() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; } static void Main() { C c = new C(); (c.getHolderForX().x, c.getHolderForY().y) = c.getDeconstructReceiver(); } public void Deconstruct(out D1 x, out D2 y) { x = new D1(); y = new D2(); Console.WriteLine(""Deconstruct""); } } class D1 { public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } "; string expected = @"getHolderforX getHolderforY getDeconstructReceiver Deconstruct Conversion1 Conversion2 setX setY "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyExecutionOrder_Deconstruct_Conditional() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; } static void Main() { C c = new C(); bool b = true; (c.getHolderForX().x, c.getHolderForY().y) = b ? c.getDeconstructReceiver() : default; } public void Deconstruct(out D1 x, out D2 y) { x = new D1(); y = new D2(); Console.WriteLine(""Deconstruct""); } } class D1 { public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } "; string expected = @"getHolderforX getHolderforY getDeconstructReceiver Deconstruct Conversion1 Conversion2 setX setY "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyExecutionOrder_TupleLiteral() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } static void Main() { C c = new C(); (c.getHolderForX().x, c.getHolderForY().y) = (new D1(), new D2()); } } class D1 { public D1() { Console.WriteLine(""Constructor1""); } public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public D2() { Console.WriteLine(""Constructor2""); } public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } "; string expected = @"getHolderforX getHolderforY Constructor1 Conversion1 Constructor2 Conversion2 setX setY "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyExecutionOrder_TupleLiteral_Conditional() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } static void Main() { C c = new C(); bool b = true; (c.getHolderForX().x, c.getHolderForY().y) = b ? (new D1(), new D2()) : default; } } class D1 { public D1() { Console.WriteLine(""Constructor1""); } public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public D2() { Console.WriteLine(""Constructor2""); } public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } "; string expected = @"getHolderforX getHolderforY Constructor1 Constructor2 Conversion1 Conversion2 setX setY "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyExecutionOrder_TupleLiteralAndDeconstruction() { string source = @" using System; class C { int w { set { Console.WriteLine($""setW""); } } int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } int z { set { Console.WriteLine($""setZ""); } } C getHolderForW() { Console.WriteLine(""getHolderforW""); return this; } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; } static void Main() { C c = new C(); (c.getHolderForW().w, (c.getHolderForY().y, c.getHolderForZ().z), c.getHolderForX().x) = (new D1(), new D2(), new D3()); } } class D1 { public D1() { Console.WriteLine(""Constructor1""); } public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public D2() { Console.WriteLine(""Constructor2""); } public void Deconstruct(out int x, out int y) { x = 2; y = 3; Console.WriteLine(""deconstruct""); } } class D3 { public D3() { Console.WriteLine(""Constructor3""); } public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; } } "; string expected = @"getHolderforW getHolderforY getHolderforZ getHolderforX Constructor1 Conversion1 Constructor2 Constructor3 Conversion3 deconstruct setW setY setZ setX "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyExecutionOrder_TupleLiteralAndDeconstruction_Conditional() { string source = @" using System; class C { int w { set { Console.WriteLine($""setW""); } } int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } int z { set { Console.WriteLine($""setZ""); } } C getHolderForW() { Console.WriteLine(""getHolderforW""); return this; } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; } static void Main() { C c = new C(); bool b = false; (c.getHolderForW().w, (c.getHolderForY().y, c.getHolderForZ().z), c.getHolderForX().x) = b ? default : (new D1(), new D2(), new D3()); } } class D1 { public D1() { Console.WriteLine(""Constructor1""); } public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public D2() { Console.WriteLine(""Constructor2""); } public void Deconstruct(out int x, out int y) { x = 2; y = 3; Console.WriteLine(""deconstruct""); } } class D3 { public D3() { Console.WriteLine(""Constructor3""); } public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; } } "; string expected = @"getHolderforW getHolderforY getHolderforZ getHolderforX Constructor1 Constructor2 Constructor3 deconstruct Conversion1 Conversion3 setW setY setZ setX "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void DifferentVariableKinds() { string source = @" class C { int[] ArrayIndexer = new int[1]; string property; string Property { set { property = value; } } string AutoProperty { get; set; } static void Main() { C c = new C(); (c.ArrayIndexer[0], c.Property, c.AutoProperty) = new C(); System.Console.WriteLine(c.ArrayIndexer[0] + "" "" + c.property + "" "" + c.AutoProperty); } public void Deconstruct(out int a, out string b, out string c) { a = 1; b = ""hello""; c = ""world""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello world"); comp.VerifyDiagnostics(); } [Fact] public void Dynamic() { string source = @" class C { dynamic Dynamic1; dynamic Dynamic2; static void Main() { C c = new C(); (c.Dynamic1, c.Dynamic2) = c; System.Console.WriteLine(c.Dynamic1 + "" "" + c.Dynamic2); } public void Deconstruct(out int a, out dynamic b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DeconstructInterfaceOnStruct() { string source = @" interface IDeconstructable { void Deconstruct(out int a, out string b); } struct C : IDeconstructable { string state; static void Main() { int x; string y; IDeconstructable c = new C() { state = ""initial"" }; System.Console.Write(c); (x, y) = c; System.Console.WriteLine("" "" + c + "" "" + x + "" "" + y); } void IDeconstructable.Deconstruct(out int a, out string b) { a = 1; b = ""hello""; state = ""modified""; } public override string ToString() { return state; } } "; var comp = CompileAndVerify(source, expectedOutput: "initial modified 1 hello", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DeconstructMethodHasParams2() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b, params int[] c) // not a Deconstruct operator { a = 1; b = ""ignored""; } public void Deconstruct(out int a, out string b) { a = 2; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "2 hello"); comp.VerifyDiagnostics(); } [Fact] public void OutParamsDisallowed() { string source = @" class C { public void Deconstruct(out int a, out string b, out params int[] c) { a = 1; b = ""ignored""; c = new[] { 2, 2 }; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,58): error CS8328: The parameter modifier 'params' cannot be used with 'out' // public void Deconstruct(out int a, out string b, out params int[] c) Diagnostic(ErrorCode.ERR_BadParameterModifiers, "params").WithArguments("params", "out").WithLocation(4, 58)); } [Fact] public void DeconstructMethodHasArglist2() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } public void Deconstruct(out int a, out string b, __arglist) // not a Deconstruct operator { a = 2; b = ""ignored""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DifferentStaticVariableKinds() { string source = @" class C { static int[] ArrayIndexer = new int[1]; static string property; static string Property { set { property = value; } } static string AutoProperty { get; set; } static void Main() { (C.ArrayIndexer[0], C.Property, C.AutoProperty) = new C(); System.Console.WriteLine(C.ArrayIndexer[0] + "" "" + C.property + "" "" + C.AutoProperty); } public void Deconstruct(out int a, out string b, out string c) { a = 1; b = ""hello""; c = ""world""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello world"); comp.VerifyDiagnostics(); } [Fact] public void DifferentVariableRefKinds() { string source = @" class C { static void Main() { long a = 1; int b; C.M(ref a, out b); System.Console.WriteLine(a + "" "" + b); } static void M(ref long a, out int b) { (a, b) = new C(); } public void Deconstruct(out int x, out byte y) { x = 2; y = (byte)3; } } "; var comp = CompileAndVerify(source, expectedOutput: "2 3"); comp.VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.RefLocalsReturns)] public void RefReturningMethod() { string source = @" class C { static int i = 0; static void Main() { (M(), M()) = new C(); System.Console.WriteLine($""Final i is {i}""); } static ref int M() { System.Console.WriteLine($""M (previous i is {i})""); return ref i; } void Deconstruct(out int x, out int y) { System.Console.WriteLine(""Deconstruct""); x = 42; y = 43; } } "; var expected = @"M (previous i is 0) M (previous i is 0) Deconstruct Final i is 43 "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact, CompilerTrait(CompilerFeature.RefLocalsReturns)] public void RefReturningProperty() { string source = @" class C { static int i = 0; static void Main() { (P, P) = new C(); System.Console.WriteLine($""Final i is {i}""); } static ref int P { get { System.Console.WriteLine($""P (previous i is {i})""); return ref i; } } void Deconstruct(out int x, out int y) { System.Console.WriteLine(""Deconstruct""); x = 42; y = 43; } } "; var expected = @"P (previous i is 0) P (previous i is 0) Deconstruct Final i is 43 "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.RefLocalsReturns)] public void RefReturningMethodFlow() { string source = @" struct C { static C i; static C P { get { System.Console.WriteLine(""getP""); return i; } set { System.Console.WriteLine(""setP""); i = value; } } static void Main() { (M(), M()) = P; } static ref C M() { System.Console.WriteLine($""M (previous i is {i})""); return ref i; } void Deconstruct(out int x, out int y) { System.Console.WriteLine(""Deconstruct""); x = 42; y = 43; } public static implicit operator C(int x) { System.Console.WriteLine(""conversion""); return new C(); } } "; var expected = @"M (previous i is C) M (previous i is C) getP Deconstruct conversion conversion"; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void Indexers() { string source = @" class C { static SomeArray array; static void Main() { int y; (Goo()[Bar()], y) = new C(); System.Console.WriteLine($""Final array values[2] {array.values[2]}""); } static SomeArray Goo() { System.Console.WriteLine($""Goo""); array = new SomeArray(); return array; } static int Bar() { System.Console.WriteLine($""Bar""); return 2; } void Deconstruct(out int x, out int y) { System.Console.WriteLine(""Deconstruct""); x = 101; y = 102; } } class SomeArray { public int[] values; public SomeArray() { values = new [] { 42, 43, 44 }; } public int this[int index] { get { System.Console.WriteLine($""indexGet (with value {values[index]})""); return values[index]; } set { System.Console.WriteLine($""indexSet (with value {value})""); values[index] = value; } } } "; var expected = @"Goo Bar Deconstruct indexSet (with value 101) Final array values[2] 101 "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void AssigningTuple() { string source = @" class C { static void Main() { long x; string y; int i = 1; (x, y) = (i, ""hello""); System.Console.WriteLine(x + "" "" + y); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); var deconstruction = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Single(); var deconstructionInfo = model.GetDeconstructionInfo(deconstruction); Assert.Null(deconstructionInfo.Method); Assert.Null(deconstructionInfo.Conversion); var nested = deconstructionInfo.Nested; Assert.Equal(2, nested.Length); Assert.Null(nested[0].Method); Assert.Equal(ConversionKind.Identity, nested[0].Conversion.Value.Kind); Assert.Empty(nested[0].Nested); Assert.Null(nested[1].Method); Assert.Equal(ConversionKind.Identity, nested[1].Conversion.Value.Kind); Assert.Empty(nested[1].Nested); var tuple = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(i, ""hello"")", tuple.ToString()); var tupleConversion = model.GetConversion(tuple); Assert.Equal(ConversionKind.ImplicitTupleLiteral, tupleConversion.Kind); Assert.Equal(ConversionKind.ImplicitNumeric, tupleConversion.UnderlyingConversions[0].Kind); } [Fact] public void AssigningTupleWithConversion() { string source = @" class C { static void Main() { long x; string y; (x, y) = M(); System.Console.WriteLine(x + "" "" + y); } static System.ValueTuple<int, string> M() { return (1, ""hello""); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); } [Fact] public void AssigningLongTuple() { string source = @" class C { static void Main() { long x; int y; (x, x, x, x, x, x, x, x, x, y) = (1, 1, 1, 1, 1, 1, 1, 1, 4, 2); System.Console.WriteLine(string.Concat(x, "" "", y)); } } "; var comp = CompileAndVerify(source, expectedOutput: "4 2"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0) //y IL_0000: ldc.i4.4 IL_0001: conv.i8 IL_0002: ldc.i4.2 IL_0003: stloc.0 IL_0004: box ""long"" IL_0009: ldstr "" "" IL_000e: ldloc.0 IL_000f: box ""int"" IL_0014: call ""string string.Concat(object, object, object)"" IL_0019: call ""void System.Console.WriteLine(string)"" IL_001e: ret }"); } [Fact] public void AssigningLongTupleWithNames() { string source = @" class C { static void Main() { long x; int y; (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); System.Console.WriteLine(x + "" "" + y); } } "; var comp = CompileAndVerify(source, expectedOutput: "9 10"); comp.VerifyDiagnostics( // (9,43): warning CS8123: The tuple element name 'a' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "a: 1").WithArguments("a", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 43), // (9,49): warning CS8123: The tuple element name 'b' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: 2").WithArguments("b", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 49), // (9,55): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 3").WithArguments("c", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 55), // (9,61): warning CS8123: The tuple element name 'd' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "d: 4").WithArguments("d", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 61), // (9,67): warning CS8123: The tuple element name 'e' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "e: 5").WithArguments("e", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 67), // (9,73): warning CS8123: The tuple element name 'f' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "f: 6").WithArguments("f", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 73), // (9,79): warning CS8123: The tuple element name 'g' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "g: 7").WithArguments("g", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 79), // (9,85): warning CS8123: The tuple element name 'h' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "h: 8").WithArguments("h", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 85), // (9,91): warning CS8123: The tuple element name 'i' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "i: 9").WithArguments("i", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 91), // (9,97): warning CS8123: The tuple element name 'j' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "j: 10").WithArguments("j", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 97) ); } [Fact] public void AssigningLongTuple2() { string source = @" class C { static void Main() { long x; int y; (x, x, x, x, x, x, x, x, x, y) = (1, 1, 1, 1, 1, 1, 1, 1, 4, (byte)2); System.Console.WriteLine(x + "" "" + y); } } "; var comp = CompileAndVerify(source, expectedOutput: "4 2"); comp.VerifyDiagnostics(); } [Fact] public void AssigningTypelessTuple() { string source = @" class C { static void Main() { string x = ""goodbye""; string y; (x, y) = (null, ""hello""); System.Console.WriteLine($""{x}{y}""); } } "; var comp = CompileAndVerify(source, expectedOutput: "hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 19 (0x13) .maxstack 2 .locals init (string V_0) //y IL_0000: ldnull IL_0001: ldstr ""hello"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""string string.Concat(string, string)"" IL_000d: call ""void System.Console.WriteLine(string)"" IL_0012: ret } "); } [Fact] public void ValueTupleReturnIsNotEmittedIfUnused() { string source = @" class C { public static void Main() { int x, y; (x, y) = new C(); } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 15 (0xf) .maxstack 3 .locals init (int V_0, int V_1) IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_0 IL_0007: ldloca.s V_1 IL_0009: callvirt ""void C.Deconstruct(out int, out int)"" IL_000e: ret }"); } [Fact] public void ValueTupleReturnIsEmittedIfUsed() { string source = @" class C { public static void Main() { int x, y; var z = ((x, y) = new C()); z.ToString(); } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x = nodes.OfType<VariableDeclaratorSyntax>().ElementAt(2); Assert.Equal("(System.Int32 x, System.Int32 y) z", model.GetDeclaredSymbol(x).ToTestDisplayString()); }; var comp = CompileAndVerify(source, sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 37 (0x25) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0, //z int V_1, int V_2) IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_1 IL_0007: ldloca.s V_2 IL_0009: callvirt ""void C.Deconstruct(out int, out int)"" IL_000e: ldloc.1 IL_000f: ldloc.2 IL_0010: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0015: stloc.0 IL_0016: ldloca.s V_0 IL_0018: constrained. ""System.ValueTuple<int, int>"" IL_001e: callvirt ""string object.ToString()"" IL_0023: pop IL_0024: ret }"); } [Fact] public void ValueTupleReturnIsEmittedIfUsed_WithCSharp7_1() { string source = @" class C { public static void Main() { int x, y; var z = ((x, y) = new C()); z.ToString(); } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x = nodes.OfType<VariableDeclaratorSyntax>().ElementAt(2); Assert.Equal("(System.Int32 x, System.Int32 y) z", model.GetDeclaredSymbol(x).ToTestDisplayString()); }; var comp = CompileAndVerify(source, sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics(); } [Fact] [WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")] public void ValueTupleNotRequiredIfReturnIsNotUsed() { string source = @" class C { public static void Main() { int x, y; (x, y) = new C(); System.Console.Write($""assignment: {x} {y}. ""); foreach (var (a, b) in new[] { new C() }) { System.Console.Write($""foreach: {a} {b}.""); } } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Regular7, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "assignment: 1 2. foreach: 1 2."); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var xy = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal("(x, y)", xy.ToString()); var tuple1 = model.GetTypeInfo(xy).Type; Assert.Equal("(System.Int32 x, System.Int32 y)[missing]", tuple1.ToTestDisplayString()); var ab = nodes.OfType<DeclarationExpressionSyntax>().Single(); var tuple2 = model.GetTypeInfo(ab).Type; Assert.Equal("(System.Int32 a, System.Int32 b)[missing]", tuple2.ToTestDisplayString()); Assert.Equal("(System.Int32 a, System.Int32 b)[missing]", model.GetTypeInfo(ab).ConvertedType.ToTestDisplayString()); } [Fact] [WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")] public void ValueTupleNotRequiredIfReturnIsNotUsed2() { string source = @" class C { public static void Main() { int x, y; for((x, y) = new C(1); ; (x, y) = new C(2)) { } } public C(int c) { } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Regular7, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var tuple1 = nodes.OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(x, y) = new C(1)", tuple1.Parent.ToString()); var tupleType1 = model.GetTypeInfo(tuple1).Type; Assert.Equal("(System.Int32 x, System.Int32 y)[missing]", tupleType1.ToTestDisplayString()); var tuple2 = nodes.OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(x, y) = new C(2)", tuple2.Parent.ToString()); var tupleType2 = model.GetTypeInfo(tuple1).Type; Assert.Equal("(System.Int32 x, System.Int32 y)[missing]", tupleType2.ToTestDisplayString()); } [Fact] [WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")] public void ValueTupleNotRequiredIfReturnIsNotUsed3() { string source = @" class C { public static void Main() { int x, y; (x, y) = new C(); } public C() { } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } namespace System { [Obsolete] public struct ValueTuple<T1, T2> { [Obsolete] public T1 Item1; [Obsolete] public T2 Item2; public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyEmitDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var tuple = nodes.OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(x, y) = new C()", tuple.Parent.ToString()); var tupleType = model.GetTypeInfo(tuple).Type; Assert.Equal("(System.Int32 x, System.Int32 y)", tupleType.ToTestDisplayString()); var underlying = ((INamedTypeSymbol)tupleType).TupleUnderlyingType; Assert.Equal("(System.Int32, System.Int32)", underlying.ToTestDisplayString()); } [Fact] [WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")] public void ValueTupleRequiredWhenRightHandSideIsTuple() { string source = @" class C { public static void Main() { int x, y; (x, y) = (1, 2); } } "; var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (7,18): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(1, 2)").WithArguments("System.ValueTuple`2").WithLocation(7, 18) ); } [Fact] [WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")] public void ValueTupleRequiredWhenRightHandSideIsTupleButNoReferenceEmitted() { string source = @" class C { public static void Main() { int x, y; (x, y) = (1, 2); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); Action<PEAssembly> assemblyValidator = assembly => { var reader = assembly.GetMetadataReader(); var names = reader.GetAssemblyRefNames().Select(name => reader.GetString(name)); Assert.Empty(names.Where(name => name.Contains("ValueTuple"))); }; CompileAndVerifyCommon(comp, assemblyValidator: assemblyValidator); } [Fact] public void ValueTupleReturnMissingMemberWithCSharp7() { string source = @" class C { public void M() { int x, y; var nested = ((x, y) = (1, 2)); System.Console.Write(nested.x); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyDiagnostics( // (8,37): error CS8305: Tuple element name 'x' is inferred. Please use language version 7.1 or greater to access an element by its inferred name. // System.Console.Write(nested.x); Diagnostic(ErrorCode.ERR_TupleInferredNamesNotAvailable, "x").WithArguments("x", "7.1").WithLocation(8, 37) ); } [Fact] public void ValueTupleReturnWithInferredNamesWithCSharp7_1() { string source = @" class C { public void M() { int x, y, Item1, Rest; var a = ((x, y) = (1, 2)); var b = ((x, x) = (1, 2)); var c = ((_, x) = (1, 2)); var d = ((Item1, Rest) = (1, 2)); var nested = ((x, Item1, y, (_, x, x), (x, y)) = (1, 2, 3, (4, 5, 6), (7, 8))); (int, int) f = ((x, y) = (1, 2)); } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var declarations = nodes.OfType<VariableDeclaratorSyntax>(); Assert.Equal("(System.Int32 x, System.Int32 y) a", model.GetDeclaredSymbol(declarations.ElementAt(4)).ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32) b", model.GetDeclaredSymbol(declarations.ElementAt(5)).ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32 x) c", model.GetDeclaredSymbol(declarations.ElementAt(6)).ToTestDisplayString()); var x = (ILocalSymbol)model.GetDeclaredSymbol(declarations.ElementAt(7)); Assert.Equal("(System.Int32, System.Int32) d", x.ToTestDisplayString()); Assert.True(x.Type.GetSymbol().TupleElementNames.IsDefault); Assert.Equal("(System.Int32 x, System.Int32, System.Int32 y, (System.Int32, System.Int32, System.Int32), (System.Int32 x, System.Int32 y)) nested", model.GetDeclaredSymbol(declarations.ElementAt(8)).ToTestDisplayString()); }; var comp = CompileAndVerify(source, sourceSymbolValidator: validator, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyDiagnostics(); } [Fact] public void DeconstructionDeclarationCanOnlyBeParsedAsStatement() { string source = @" class C { public static void Main() { var z = ((var x, int y) = new C()); } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,19): error CS8185: A declaration is not allowed in this context. // var z = ((var x, int y) = new C()); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x").WithLocation(6, 19) ); } [ConditionalFact(typeof(DesktopOnly))] public void Constraints_01() { string source = @" using System; class C { public void M() { (int x, var (err1, y)) = (0, new C()); // ok, no return value used (ArgIterator err2, var err3) = M2(); // ok, no return value foreach ((ArgIterator err4, var err5) in new[] { M2() }) // ok, no return value { } } public static (ArgIterator, ArgIterator) M2() { return (default(ArgIterator), default(ArgIterator)); } public void Deconstruct(out ArgIterator a, out int b) { a = default(ArgIterator); b = 2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (19,29): error CS1601: Cannot make reference to variable of type 'ArgIterator' // public void Deconstruct(out ArgIterator a, out int b) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out ArgIterator a").WithArguments("System.ArgIterator").WithLocation(19, 29), // (14,46): error CS0306: The type 'ArgIterator' may not be used as a type argument // public static (ArgIterator, ArgIterator) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("System.ArgIterator").WithLocation(14, 46), // (14,46): error CS0306: The type 'ArgIterator' may not be used as a type argument // public static (ArgIterator, ArgIterator) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("System.ArgIterator").WithLocation(14, 46), // (16,17): error CS0306: The type 'ArgIterator' may not be used as a type argument // return (default(ArgIterator), default(ArgIterator)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(ArgIterator)").WithArguments("System.ArgIterator").WithLocation(16, 17), // (16,39): error CS0306: The type 'ArgIterator' may not be used as a type argument // return (default(ArgIterator), default(ArgIterator)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(ArgIterator)").WithArguments("System.ArgIterator").WithLocation(16, 39) ); } [Fact] public void Constraints_02() { string source = @" unsafe class C { public void M() { (int x, var (err1, y)) = (0, new C()); // ok, no return value (var err2, var err3) = M2(); // ok, no return value foreach ((var err4, var err5) in new[] { M2() }) // ok, no return value { } } public static (int*, int*) M2() { return (default(int*), default(int*)); } public void Deconstruct(out int* a, out int b) { a = default(int*); b = 2; } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (13,32): error CS0306: The type 'int*' may not be used as a type argument // public static (int*, int*) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(13, 32), // (13,32): error CS0306: The type 'int*' may not be used as a type argument // public static (int*, int*) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(13, 32), // (15,17): error CS0306: The type 'int*' may not be used as a type argument // return (default(int*), default(int*)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(int*)").WithArguments("int*").WithLocation(15, 17), // (15,32): error CS0306: The type 'int*' may not be used as a type argument // return (default(int*), default(int*)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(int*)").WithArguments("int*").WithLocation(15, 32) ); } [Fact] public void Constraints_03() { string source = @" unsafe class C { public void M() { int ok; int* err1, err2; var t = ((ok, (err1, ok)) = (0, new C())); var t2 = ((err1, err2) = M2()); } public static (int*, int*) M2() { throw null; } public void Deconstruct(out int* a, out int b) { a = default(int*); b = 2; } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (12,32): error CS0306: The type 'int*' may not be used as a type argument // public static (int*, int*) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(12, 32), // (12,32): error CS0306: The type 'int*' may not be used as a type argument // public static (int*, int*) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(12, 32), // (8,24): error CS0306: The type 'int*' may not be used as a type argument // var t = ((ok, (err1, ok)) = (0, new C())); Diagnostic(ErrorCode.ERR_BadTypeArgument, "err1").WithArguments("int*").WithLocation(8, 24), // (9,20): error CS0306: The type 'int*' may not be used as a type argument // var t2 = ((err1, err2) = M2()); Diagnostic(ErrorCode.ERR_BadTypeArgument, "err1").WithArguments("int*").WithLocation(9, 20), // (9,26): error CS0306: The type 'int*' may not be used as a type argument // var t2 = ((err1, err2) = M2()); Diagnostic(ErrorCode.ERR_BadTypeArgument, "err2").WithArguments("int*").WithLocation(9, 26) ); } [Fact] public void DeconstructionWithTupleNamesCannotBeParsed() { string source = @" class C { public static void Main() { (Alice: var x, Bob: int y) = (1, 2); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,10): error CS8187: Tuple element names are not permitted on the left of a deconstruction. // (Alice: var x, Bob: int y) = (1, 2); Diagnostic(ErrorCode.ERR_TupleElementNamesInDeconstruction, "Alice:").WithLocation(6, 10), // (6,24): error CS8187: Tuple element names are not permitted on the left of a deconstruction. // (Alice: var x, Bob: int y) = (1, 2); Diagnostic(ErrorCode.ERR_TupleElementNamesInDeconstruction, "Bob:").WithLocation(6, 24) ); } [Fact] public void ValueTupleReturnIsEmittedIfUsedInLambda() { string source = @" class C { static void F(System.Action a) { } static void F<T>(System.Func<T> f) { System.Console.Write(f().ToString()); } static void Main() { int x, y; F(() => (x, y) = (1, 2)); } } "; var comp = CompileAndVerify(source, expectedOutput: "(1, 2)"); comp.VerifyDiagnostics(); } [Fact] public void AssigningIntoProperties() { string source = @" class C { static int field; static long x { set { System.Console.WriteLine($""setX {value}""); } } static string y { get; set; } static ref int z { get { return ref field; } } static void Main() { (x, y, z) = new C(); System.Console.WriteLine(y); System.Console.WriteLine($""field: {field}""); } public void Deconstruct(out int a, out string b, out int c) { a = 1; b = ""hello""; c = 2; } } "; string expected = @"setX 1 hello field: 2 "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void AssigningTupleIntoProperties() { string source = @" class C { static int field; static long x { set { System.Console.WriteLine($""setX {value}""); } } static string y { get; set; } static ref int z { get { return ref field; } } static void Main() { (x, y, z) = (1, ""hello"", 2); System.Console.WriteLine(y); System.Console.WriteLine($""field: {field}""); } } "; string expected = @"setX 1 hello field: 2 "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] [WorkItem(18554, "https://github.com/dotnet/roslyn/issues/18554")] public void AssigningIntoIndexers() { string source = @" using System; class C { int field; ref int this[int x, int y, int z, int opt = 1] { get { Console.WriteLine($""this.get""); return ref field; } } int this[int x, long y, int z, int opt = 1] { set { Console.WriteLine($""this.set({value})""); } } int M(int i) { Console.WriteLine($""M({i})""); return 0; } void Test() { (this[z: M(1), x: M(2), y: 10], this[z: M(3), x: M(4), y: 10L]) = this; Console.WriteLine($""field: {field}""); } static void Main() { new C().Test(); } void Deconstruct(out int a, out int b) { Console.WriteLine(nameof(Deconstruct)); a = 1; b = 2; } } "; var expectedOutput = @"M(1) M(2) this.get M(3) M(4) Deconstruct this.set(2) field: 1 "; var comp = CompileAndVerify(source, expectedOutput: expectedOutput); comp.VerifyDiagnostics(); } [Fact] [WorkItem(18554, "https://github.com/dotnet/roslyn/issues/18554")] public void AssigningTupleIntoIndexers() { string source = @" using System; class C { int field; ref int this[int x, int y, int z, int opt = 1] { get { Console.WriteLine($""this.get""); return ref field; } } int this[int x, long y, int z, int opt = 1] { set { Console.WriteLine($""this.set({value})""); } } int M(int i) { Console.WriteLine($""M({i})""); return 0; } void Test() { (this[z: M(1), x: M(2), y: 10], this[z: M(3), x: M(4), y: 10L]) = (1, 2); Console.WriteLine($""field: {field}""); } static void Main() { new C().Test(); } } "; var expectedOutput = @"M(1) M(2) this.get M(3) M(4) this.set(2) field: 1 "; var comp = CompileAndVerify(source, expectedOutput: expectedOutput); comp.VerifyDiagnostics(); } [Fact] public void AssigningIntoIndexerWithOptionalValueParameter() { var ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6d 00 00 ) .method public hidebysig specialname instance void set_Item ( int32 i, [opt] int32 'value' ) cil managed { .param [2] = int32(1) .maxstack 8 IL_0000: ldstr ""this.set({0})"" IL_0005: ldarg.2 IL_0006: box[mscorlib]System.Int32 IL_000b: call string[mscorlib] System.String::Format(string, object) IL_0010: call void [mscorlib]System.Console::WriteLine(string) IL_0015: ret } // end of method C::set_Item .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor .property instance int32 Item( int32 i ) { .set instance void C::set_Item(int32, int32) } } // end of class C "; var source = @" class Program { static void Main() { var c = new C(); (c[1], c[2]) = (1, 2); } } "; string expectedOutput = @"this.set(1) this.set(2) "; var comp = CreateCompilationWithILAndMscorlib40(source, ilSource, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: expectedOutput).VerifyDiagnostics(); } [Fact] public void Swap() { string source = @" class C { static int x = 2; static int y = 4; static void Main() { Swap(); System.Console.WriteLine(x + "" "" + y); } static void Swap() { (x, y) = (y, x); } } "; var comp = CompileAndVerify(source, expectedOutput: "4 2"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Swap", @" { // Code size 23 (0x17) .maxstack 2 .locals init (int V_0) IL_0000: ldsfld ""int C.y"" IL_0005: ldsfld ""int C.x"" IL_000a: stloc.0 IL_000b: stsfld ""int C.x"" IL_0010: ldloc.0 IL_0011: stsfld ""int C.y"" IL_0016: ret } "); } [Fact] public void CircularFlow() { string source = @" class C { static void Main() { (object i, object ii) x = (1, 2); object y; (x.ii, y) = x; System.Console.WriteLine(x + "" "" + y); } } "; var comp = CompileAndVerify(source, expectedOutput: "(1, 1) 2"); comp.VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.RefLocalsReturns)] public void CircularFlow2() { string source = @" class C { static void Main() { (object i, object ii) x = (1,2); object y; ref var a = ref x; (a.ii, y) = x; System.Console.WriteLine(x + "" "" + y); } } "; var comp = CompileAndVerify(source, expectedOutput: "(1, 1) 2", parseOptions: TestOptions.Regular.WithRefsFeature()); comp.VerifyDiagnostics(); } [Fact] public void DeconstructUsingBaseDeconstructMethod() { string source = @" class Base { public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } class C : Base { static void Main() { int x, y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int c) { c = 42; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2", parseOptions: TestOptions.Regular.WithRefsFeature()); comp.VerifyDiagnostics(); } [Fact] public void NestedDeconstructUsingSystemTupleExtensionMethod() { string source = @" using System; class C { static void Main() { int x; string y, z; (x, (y, z)) = Tuple.Create(1, Tuple.Create(""hello"", ""world"")); System.Console.WriteLine(x + "" "" + y + "" "" + z); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello world", parseOptions: TestOptions.Regular.WithRefsFeature()); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); var deconstruction = (AssignmentExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.SimpleAssignmentExpression).AsNode(); Assert.Equal(@"(x, (y, z)) = Tuple.Create(1, Tuple.Create(""hello"", ""world""))", deconstruction.ToString()); var deconstructionInfo = model.GetDeconstructionInfo(deconstruction); Assert.Equal("void System.TupleExtensions.Deconstruct<System.Int32, System.Tuple<System.String, System.String>>(" + "this System.Tuple<System.Int32, System.Tuple<System.String, System.String>> value, " + "out System.Int32 item1, out System.Tuple<System.String, System.String> item2)", deconstructionInfo.Method.ToTestDisplayString()); Assert.Null(deconstructionInfo.Conversion); var nested = deconstructionInfo.Nested; Assert.Equal(2, nested.Length); Assert.Null(nested[0].Method); Assert.Equal(ConversionKind.Identity, nested[0].Conversion.Value.Kind); Assert.Empty(nested[0].Nested); Assert.Equal("void System.TupleExtensions.Deconstruct<System.String, System.String>(" + "this System.Tuple<System.String, System.String> value, " + "out System.String item1, out System.String item2)", nested[1].Method.ToTestDisplayString()); Assert.Null(nested[1].Conversion); var nested2 = nested[1].Nested; Assert.Equal(2, nested.Length); Assert.Null(nested2[0].Method); Assert.Equal(ConversionKind.Identity, nested2[0].Conversion.Value.Kind); Assert.Empty(nested2[0].Nested); Assert.Null(nested2[1].Method); Assert.Equal(ConversionKind.Identity, nested2[1].Conversion.Value.Kind); Assert.Empty(nested2[1].Nested); } [Fact] public void DeconstructUsingValueTupleExtensionMethod() { string source = @" class C { static void Main() { int x; string y, z; (x, y, z) = (1, 2); } } public static class Extensions { public static void Deconstruct(this (int, int) self, out int x, out string y, out string z) { throw null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,25): error CS0029: Cannot implicitly convert type 'int' to 'string' // (x, y, z) = (1, 2); Diagnostic(ErrorCode.ERR_NoImplicitConv, "2").WithArguments("int", "string").WithLocation(8, 25), // (8,9): error CS8132: Cannot deconstruct a tuple of '2' elements into '3' variables. // (x, y, z) = (1, 2); Diagnostic(ErrorCode.ERR_DeconstructWrongCardinality, "(x, y, z) = (1, 2)").WithArguments("2", "3").WithLocation(8, 9) ); } [Fact] public void OverrideDeconstruct() { string source = @" class Base { public virtual void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } class C : Base { static void Main() { int x; string y; (x, y) = new C(); } public override void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; System.Console.WriteLine(""override""); } } "; var comp = CompileAndVerify(source, expectedOutput: "override", parseOptions: TestOptions.Regular.WithRefsFeature()); comp.VerifyDiagnostics(); } [Fact] public void DeconstructRefTuple() { string template = @" using System; class C { static void Main() { int VARIABLES; // int x1, x2, ... (VARIABLES) = (TUPLE).ToTuple(); // (x1, x2, ...) = (1, 2, ...).ToTuple(); System.Console.WriteLine(OUTPUT); } } "; for (int i = 2; i <= 21; i++) { var tuple = String.Join(", ", Enumerable.Range(1, i).Select(n => n.ToString())); var variables = String.Join(", ", Enumerable.Range(1, i).Select(n => $"x{n}")); var output = String.Join(@" + "" "" + ", Enumerable.Range(1, i).Select(n => $"x{n}")); var expected = String.Join(" ", Enumerable.Range(1, i).Select(n => n)); var source = template.Replace("VARIABLES", variables).Replace("TUPLE", tuple).Replace("OUTPUT", output); var comp = CompileAndVerify(source, expectedOutput: expected, parseOptions: TestOptions.Regular.WithRefsFeature()); comp.VerifyDiagnostics(); } } [Fact] public void DeconstructExtensionMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } } static class D { public static void Deconstruct(this C value, out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); } [Fact] public void DeconstructRefExtensionMethod() { // https://github.com/dotnet/csharplang/blob/main/meetings/2018/LDM-2018-01-24.md string source = @" struct C { static void Main() { long x; string y; var c = new C(); (x, y) = c; System.Console.WriteLine(x + "" "" + y); } } static class D { public static void Deconstruct(this ref C value, out int a, out string b) { a = 1; b = ""hello""; } } "; CreateCompilation(source).VerifyDiagnostics( // (10,9): error CS1510: A ref or out value must be an assignable variable // (x, y) = c; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x, y) = c").WithLocation(10, 9) ); } [Fact] public void DeconstructInExtensionMethod() { string source = @" struct C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } } static class D { public static void Deconstruct(this in C value, out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); } [Fact] public void UnderspecifiedDeconstructGenericExtensionMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); } } static class Extension { public static void Deconstruct<T>(this C value, out int a, out T b) { a = 2; b = default(T); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS0411: The type arguments for method 'Extension.Deconstruct<T>(C, out int, out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // (x, y) = new C(); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "new C()").WithArguments("Extension.Deconstruct<T>(C, out int, out T)").WithLocation(8, 18), // (8,18): error CS8129: No Deconstruct instance or extension method was found for type 'C', with 2 out parameters. // (x, y) = new C(); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 18) ); } [Fact] public void UnspecifiedGenericMethodIsNotCandidate() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); } } static class Extension { public static void Deconstruct<T>(this C value, out int a, out T b) { a = 2; b = default(T); } public static void Deconstruct(this C value, out int a, out string b) { a = 2; b = ""hello""; System.Console.Write(""Deconstructed""); } }"; var comp = CompileAndVerify(source, expectedOutput: "Deconstructed"); comp.VerifyDiagnostics(); } [Fact] public void DeconstructGenericExtensionMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C1<string>(); } } public class C1<T> { } static class Extension { public static void Deconstruct<T>(this C1<T> value, out int a, out T b) { a = 2; b = default(T); System.Console.WriteLine(""Deconstructed""); } } "; var comp = CompileAndVerify(source, expectedOutput: "Deconstructed"); comp.VerifyDiagnostics(); } [Fact] public void DeconstructGenericMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C1(); } } class C1 { public void Deconstruct<T>(out int a, out T b) { a = 2; b = default(T); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,18): error CS0411: The type arguments for method 'C1.Deconstruct<T>(out int, out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // (x, y) = new C1(); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "new C1()").WithArguments("C1.Deconstruct<T>(out int, out T)").WithLocation(9, 18), // (9,18): error CS8129: No Deconstruct instance or extension method was found for type 'C1', with 2 out parameters and a void return type. // (x, y) = new C1(); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C1()").WithArguments("C1", "2").WithLocation(9, 18) ); } [Fact] public void AmbiguousDeconstructGenericMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C1(); System.Console.Write($""{x} {y}""); } } class C1 { public void Deconstruct<T>(out int a, out T b) { a = 2; b = default(T); } public void Deconstruct(out int a, out string b) { a = 2; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "2 hello"); comp.VerifyDiagnostics(); } [Fact] public void NestedTupleAssignment() { string source = @" class C { static void Main() { long x; string y, z; (x, (y, z)) = ((int)1, (""a"", ""b"")); System.Console.WriteLine(x + "" "" + y + "" "" + z); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(x, (y, z))", lhs.ToString()); Assert.Equal("(System.Int64 x, (System.String y, System.String z))", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int64 x, (System.String y, System.String z))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); }; var comp = CompileAndVerify(source, expectedOutput: "1 a b", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void NestedTypelessTupleAssignment() { string source = @" class C { static void Main() { string x, y, z; (x, (y, z)) = (null, (null, null)); System.Console.WriteLine(""nothing"" + x + y + z); } } "; var comp = CompileAndVerify(source, expectedOutput: "nothing"); comp.VerifyDiagnostics(); } [Fact] public void NestedDeconstructAssignment() { string source = @" class C { static void Main() { int x; string y, z; (x, (y, z)) = new D1(); System.Console.WriteLine(x + "" "" + y + "" "" + z); } } class D1 { public void Deconstruct(out int item1, out D2 item2) { item1 = 1; item2 = new D2(); } } class D2 { public void Deconstruct(out string item1, out string item2) { item1 = ""a""; item2 = ""b""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 a b"); comp.VerifyDiagnostics(); } [Fact] public void NestedMixedAssignment1() { string source = @" class C { static void Main() { int x, y, z; (x, (y, z)) = (1, new D1()); System.Console.WriteLine(x + "" "" + y + "" "" + z); } } class D1 { public void Deconstruct(out int item1, out int item2) { item1 = 2; item2 = 3; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2 3"); comp.VerifyDiagnostics(); } [Fact] public void NestedMixedAssignment2() { string source = @" class C { static void Main() { int x; string y, z; (x, (y, z)) = new D1(); System.Console.WriteLine(x + "" "" + y + "" "" + z); } } class D1 { public void Deconstruct(out int item1, out (string, string) item2) { item1 = 1; item2 = (""a"", ""b""); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 a b"); comp.VerifyDiagnostics(); } [Fact] public void VerifyNestedExecutionOrder() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } int z { set { Console.WriteLine($""setZ""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; } C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; } static void Main() { C c = new C(); (c.getHolderForX().x, (c.getHolderForY().y, c.getHolderForZ().z)) = c.getDeconstructReceiver(); } public void Deconstruct(out D1 x, out C1 t) { x = new D1(); t = new C1(); Console.WriteLine(""Deconstruct1""); } } class C1 { public void Deconstruct(out D2 y, out D3 z) { y = new D2(); z = new D3(); Console.WriteLine(""Deconstruct2""); } } class D1 { public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } class D3 { public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; } } "; string expected = @"getHolderforX getHolderforY getHolderforZ getDeconstructReceiver Deconstruct1 Deconstruct2 Conversion1 Conversion2 Conversion3 setX setY setZ "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyNestedExecutionOrder_Conditional() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } int z { set { Console.WriteLine($""setZ""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; } C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; } static void Main() { C c = new C(); bool b = false; (c.getHolderForX().x, (c.getHolderForY().y, c.getHolderForZ().z)) = b ? default : c.getDeconstructReceiver(); } public void Deconstruct(out D1 x, out C1 t) { x = new D1(); t = new C1(); Console.WriteLine(""Deconstruct1""); } } class C1 { public void Deconstruct(out D2 y, out D3 z) { y = new D2(); z = new D3(); Console.WriteLine(""Deconstruct2""); } } class D1 { public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } class D3 { public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; } } "; string expected = @"getHolderforX getHolderforY getHolderforZ getDeconstructReceiver Deconstruct1 Deconstruct2 Conversion1 Conversion2 Conversion3 setX setY setZ "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyNestedExecutionOrder2() { string source = @" using System; class C { static LongInteger x1 { set { Console.WriteLine($""setX1 {value}""); } } static LongInteger x2 { set { Console.WriteLine($""setX2 {value}""); } } static LongInteger x3 { set { Console.WriteLine($""setX3 {value}""); } } static LongInteger x4 { set { Console.WriteLine($""setX4 {value}""); } } static LongInteger x5 { set { Console.WriteLine($""setX5 {value}""); } } static LongInteger x6 { set { Console.WriteLine($""setX6 {value}""); } } static LongInteger x7 { set { Console.WriteLine($""setX7 {value}""); } } static void Main() { ((x1, (x2, x3)), ((x4, x5), (x6, x7))) = Pair.Create(Pair.Create(new Integer(1), Pair.Create(new Integer(2), new Integer(3))), Pair.Create(Pair.Create(new Integer(4), new Integer(5)), Pair.Create(new Integer(6), new Integer(7)))); } } " + commonSource; string expected = @"Deconstructing ((1, (2, 3)), ((4, 5), (6, 7))) Deconstructing (1, (2, 3)) Deconstructing (2, 3) Deconstructing ((4, 5), (6, 7)) Deconstructing (4, 5) Deconstructing (6, 7) Converting 1 Converting 2 Converting 3 Converting 4 Converting 5 Converting 6 Converting 7 setX1 1 setX2 2 setX3 3 setX4 4 setX5 5 setX6 6 setX7 7"; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void MixOfAssignments() { string source = @" class C { static void Main() { long x; string y; C a, b, c; c = new C(); (x, y) = a = b = c; System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/12400")] [WorkItem(12400, "https://github.com/dotnet/roslyn/issues/12400")] public void AssignWithPostfixOperator() { string source = @" class C { int state = 1; static void Main() { long x; string y; C c = new C(); (x, y) = c++; System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = state; b = ""hello""; } public static C operator ++(C c1) { return new C() { state = 2 }; } } "; // https://github.com/dotnet/roslyn/issues/12400 // we expect "2 hello" instead, which means the evaluation order is wrong var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); } [Fact] [WorkItem(13631, "https://github.com/dotnet/roslyn/issues/13631")] public void DeconstructionDeclaration() { string source = @" class C { static void Main() { var (x1, x2) = (1, ""hello""); System.Console.WriteLine(x1 + "" "" + x2); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 32 (0x20) .maxstack 3 .locals init (int V_0, //x1 string V_1) //x2 IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldstr ""hello"" IL_0007: stloc.1 IL_0008: ldloca.s V_0 IL_000a: call ""string int.ToString()"" IL_000f: ldstr "" "" IL_0014: ldloc.1 IL_0015: call ""string string.Concat(string, string, string)"" IL_001a: call ""void System.Console.WriteLine(string)"" IL_001f: ret }"); } [Fact] public void NestedVarDeconstructionDeclaration() { string source = @" class C { static void Main() { var (x1, (x2, x3)) = (1, (2, ""hello"")); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().First(); Assert.Equal(@"var (x1, (x2, x3))", lhs.ToString()); Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhs).Symbol); var lhsNested = tree.GetRoot().DescendantNodes().OfType<ParenthesizedVariableDesignationSyntax>().ElementAt(1); Assert.Equal(@"(x2, x3)", lhsNested.ToString()); Assert.Null(model.GetTypeInfo(lhsNested).Type); Assert.Null(model.GetSymbolInfo(lhsNested).Symbol); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); }; var comp = CompileAndVerify(source, expectedOutput: "1 2 hello", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void NestedVarDeconstructionDeclaration_WithCSharp7_1() { string source = @" class C { static void Main() { (int x1, var (x2, (x3, x4)), var x5) = (1, (2, (3, ""hello"")), 5); System.Console.WriteLine($""{x1} {x2} {x3} {x4} {x5}""); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(int x1, var (x2, (x3, x4)), var x5)", lhs.ToString()); Assert.Equal("(System.Int32 x1, (System.Int32 x2, (System.Int32 x3, System.String x4)), System.Int32 x5)", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhs).Symbol); var x234 = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(1); Assert.Equal(@"var (x2, (x3, x4))", x234.ToString()); Assert.Equal("(System.Int32 x2, (System.Int32 x3, System.String x4))", model.GetTypeInfo(x234).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x234).Symbol); var x34 = tree.GetRoot().DescendantNodes().OfType<ParenthesizedVariableDesignationSyntax>().ElementAt(1); Assert.Equal(@"(x3, x4)", x34.ToString()); Assert.Null(model.GetTypeInfo(x34).Type); Assert.Null(model.GetSymbolInfo(x34).Symbol); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); var x4 = GetDeconstructionVariable(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForDeconstructionLocal(model, x4, x4Ref); var x5 = GetDeconstructionVariable(tree, "x5"); var x5Ref = GetReference(tree, "x5"); VerifyModelForDeconstructionLocal(model, x5, x5Ref); }; var comp = CompileAndVerify(source, expectedOutput: "1 2 3 hello 5", sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics(); } [Fact] public void NestedVarDeconstructionAssignment_WithCSharp7_1() { string source = @" class C { static void Main() { int x1, x2, x3; (x1, (x2, x3)) = (1, (2, 3)); System.Console.WriteLine($""{x1} {x2} {x3}""); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x123 = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(x1, (x2, x3))", x123.ToString()); Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.Int32 x3))", model.GetTypeInfo(x123).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x123).Symbol); var x23 = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(x2, x3)", x23.ToString()); Assert.Equal("(System.Int32 x2, System.Int32 x3)", model.GetTypeInfo(x23).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x23).Symbol); }; var comp = CompileAndVerify(source, expectedOutput: "1 2 3", sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics(); } [Fact] public void NestedVarDeconstructionDeclaration2() { string source = @" class C { static void Main() { (var x1, var (x2, x3)) = (1, (2, ""hello"")); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal("(var x1, var (x2, x3))", lhs.ToString()); Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhs).Symbol); var lhsNested = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(1); Assert.Equal("var (x2, x3)", lhsNested.ToString()); Assert.Equal("(System.Int32 x2, System.String x3)", model.GetTypeInfo(lhsNested).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 x2, System.String x3)", model.GetTypeInfo(lhsNested).ConvertedType.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhsNested).Symbol); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); }; var comp = CompileAndVerify(source, expectedOutput: "1 2 hello", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void NestedVarDeconstructionDeclarationWithCSharp7_1() { string source = @" class C { static void Main() { (var x1, byte _, var (x2, x3)) = (1, 2, (3, ""hello"")); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal("(var x1, byte _, var (x2, x3))", lhs.ToString()); Assert.Equal("(System.Int32 x1, System.Byte, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 x1, System.Byte, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhs).Symbol); var lhsNested = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(2); Assert.Equal("var (x2, x3)", lhsNested.ToString()); Assert.Equal("(System.Int32 x2, System.String x3)", model.GetTypeInfo(lhsNested).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhsNested).Symbol); }; var comp = CompileAndVerify(source, sourceSymbolValidator: validator, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyDiagnostics(); } [Fact] public void NestedDeconstructionDeclaration() { string source = @" class C { static void Main() { (int x1, (int x2, string x3)) = (1, (2, ""hello"")); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); }; var comp = CompileAndVerify(source, expectedOutput: "1 2 hello", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void VarMethodExists() { string source = @" class C { static void Main() { int x1 = 1; int x2 = 1; var (x1, x2); } static void var(int a, int b) { System.Console.WriteLine(""var""); } } "; var comp = CompileAndVerify(source, expectedOutput: "var"); comp.VerifyDiagnostics(); } [Fact] public void TypeMergingSuccess1() { string source = @" class C { static void Main() { (var (x1, x2), string x3) = ((1, 2), null); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; var comp = CompileAndVerify(source, expectedOutput: " 1 2"); comp.VerifyDiagnostics(); } [Fact] public void TypeMergingSuccess2() { string source = @" class C { static void Main() { (string x1, byte x2, var x3) = (null, 2, 3); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(string x1, byte x2, var x3)", lhs.ToString()); Assert.Equal("(System.String x1, System.Byte x2, System.Int32 x3)", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); var literal = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(null, 2, 3)", literal.ToString()); Assert.Null(model.GetTypeInfo(literal).Type); Assert.Equal("(System.String, System.Byte, System.Int32)", model.GetTypeInfo(literal).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(literal).Kind); }; var comp = CompileAndVerify(source, expectedOutput: " 2 3", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void TypeMergingSuccess3() { string source = @" class C { static void Main() { (string x1, var x2) = (null, (1, 2)); System.Console.WriteLine(x1 + "" "" + x2); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(string x1, var x2)", lhs.ToString()); Assert.Equal("(System.String x1, (System.Int32, System.Int32) x2)", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); var literal = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(null, (1, 2))", literal.ToString()); Assert.Null(model.GetTypeInfo(literal).Type); Assert.Equal("(System.String, (System.Int32, System.Int32))", model.GetTypeInfo(literal).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(literal).Kind); var nestedLiteral = literal.Arguments[1].Expression; Assert.Equal(@"(1, 2)", nestedLiteral.ToString()); Assert.Equal("(System.Int32, System.Int32)", model.GetTypeInfo(nestedLiteral).Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", model.GetTypeInfo(nestedLiteral).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(nestedLiteral).Kind); }; var comp = CompileAndVerify(source, expectedOutput: " (1, 2)", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void TypeMergingSuccess4() { string source = @" class C { static void Main() { ((string x1, byte x2, var x3), int x4) = (M(), 4); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4); } static (string, byte, int) M() { return (null, 2, 3); } } "; var comp = CompileAndVerify(source, expectedOutput: " 2 3 4"); comp.VerifyDiagnostics(); } [Fact] public void VarVarDeclaration() { string source = @" class C { static void Main() { (var (x1, x2), var x3) = Pair.Create(Pair.Create(1, ""hello""), 2); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } " + commonSource; string expected = @"Deconstructing ((1, hello), 2) Deconstructing (1, hello) 1 hello 2"; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); }; var comp = CompileAndVerify(source, expectedOutput: expected, parseOptions: TestOptions.Regular, sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } private static void VerifyModelForDeconstructionLocal(SemanticModel model, SingleVariableDesignationSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForDeconstruction(model, decl, LocalDeclarationKind.DeconstructionVariable, references); } private static void VerifyModelForLocal(SemanticModel model, SingleVariableDesignationSyntax decl, LocalDeclarationKind kind, params IdentifierNameSyntax[] references) { VerifyModelForDeconstruction(model, decl, kind, references); } private static void VerifyModelForDeconstructionForeach(SemanticModel model, SingleVariableDesignationSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForDeconstruction(model, decl, LocalDeclarationKind.ForEachIterationVariable, references); } private static void VerifyModelForDeconstruction(SemanticModel model, SingleVariableDesignationSyntax decl, LocalDeclarationKind kind, params IdentifierNameSyntax[] references) { var symbol = model.GetDeclaredSymbol(decl); Assert.Equal(decl.Identifier.ValueText, symbol.Name); Assert.Equal(kind, symbol.GetSymbol<LocalSymbol>().DeclarationKind); Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)decl)); Assert.Same(symbol, model.LookupSymbols(decl.SpanStart, name: decl.Identifier.ValueText).Single()); Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier.ValueText)); var local = symbol.GetSymbol<SourceLocalSymbol>(); var typeSyntax = GetTypeSyntax(decl); if (local.IsVar && local.Type.IsErrorType()) { Assert.Null(model.GetSymbolInfo(typeSyntax).Symbol); } else { if (typeSyntax != null) { Assert.Equal(local.Type.GetPublicSymbol(), model.GetSymbolInfo(typeSyntax).Symbol); } } foreach (var reference in references) { Assert.Same(symbol, model.GetSymbolInfo(reference).Symbol); Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: decl.Identifier.ValueText).Single()); Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier.ValueText)); Assert.Equal(local.Type.GetPublicSymbol(), model.GetTypeInfo(reference).Type); } } private static void VerifyModelForDeconstructionField(SemanticModel model, SingleVariableDesignationSyntax decl, params IdentifierNameSyntax[] references) { var field = (IFieldSymbol)model.GetDeclaredSymbol(decl); Assert.Equal(decl.Identifier.ValueText, field.Name); Assert.Equal(SymbolKind.Field, field.Kind); Assert.Same(field, model.GetDeclaredSymbol((SyntaxNode)decl)); Assert.Same(field, model.LookupSymbols(decl.SpanStart, name: decl.Identifier.ValueText).Single()); Assert.Equal(Accessibility.Private, field.DeclaredAccessibility); Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier.ValueText)); foreach (var reference in references) { Assert.Same(field, model.GetSymbolInfo(reference).Symbol); Assert.Same(field, model.LookupSymbols(reference.SpanStart, name: decl.Identifier.ValueText).Single()); Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier.ValueText)); Assert.Equal(field.Type, model.GetTypeInfo(reference).Type); } } private static TypeSyntax GetTypeSyntax(SingleVariableDesignationSyntax decl) { return (decl.Parent as DeclarationExpressionSyntax)?.Type; } private static SingleVariableDesignationSyntax GetDeconstructionVariable(SyntaxTree tree, string name) { return tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == name).Single(); } private static IEnumerable<DiscardDesignationSyntax> GetDiscardDesignations(SyntaxTree tree) { return tree.GetRoot().DescendantNodes().OfType<DiscardDesignationSyntax>(); } private static IEnumerable<IdentifierNameSyntax> GetDiscardIdentifiers(SyntaxTree tree) { return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(i => i.Identifier.ContextualKind() == SyntaxKind.UnderscoreToken); } private static IdentifierNameSyntax GetReference(SyntaxTree tree, string name) { return GetReferences(tree, name).Single(); } private static IdentifierNameSyntax[] GetReferences(SyntaxTree tree, string name, int count) { var nameRef = GetReferences(tree, name).ToArray(); Assert.Equal(count, nameRef.Length); return nameRef; } private static IEnumerable<IdentifierNameSyntax> GetReferences(SyntaxTree tree, string name) { return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == name); } [Fact] public void DeclarationWithActualVarType() { string source = @" class C { static void Main() { (var x1, int x2) = (new var(), 2); System.Console.WriteLine(x1 + "" "" + x2); } } class var { public override string ToString() { return ""var""; } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); // extra checks on x1 var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("var", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); // extra checks on x2 var x2Type = GetTypeSyntax(x2); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString()); }; var comp = CompileAndVerify(source, expectedOutput: "var 2", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void DeclarationWithImplicitVarType() { string source = @" class C { static void Main() { (var x1, var x2) = (1, 2); var (x3, x4) = (3, 4); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); var x4 = GetDeconstructionVariable(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForDeconstructionLocal(model, x4, x4Ref); // extra checks on x1 var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(x1Type)); var x34Var = (DeclarationExpressionSyntax)x3.Parent.Parent; Assert.Equal("var", x34Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x34Var.Type).Symbol); // The var in `var (x3, x4)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void DeclarationWithAliasedVarType() { string source = @" using var = D; class C { static void Main() { (var x1, int x2) = (new var(), 2); System.Console.WriteLine(x1 + "" "" + x2); } } class D { public override string ToString() { return ""var""; } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); // extra checks on x1 var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("D", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); var x1Alias = model.GetAliasInfo(x1Type); Assert.Equal(SymbolKind.NamedType, x1Alias.Target.Kind); Assert.Equal("D", x1Alias.Target.ToDisplayString()); // extra checks on x2 var x2Type = GetTypeSyntax(x2); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(x2Type)); }; var comp = CompileAndVerify(source, expectedOutput: "var 2", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void ForWithImplicitVarType() { string source = @" class C { static void Main() { for (var (x1, x2) = (1, 2); x1 < 2; (x1, x2) = (x1 + 1, x2 + 1)) { System.Console.WriteLine(x1 + "" "" + x2); } } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 4); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReferences(tree, "x2", 3); VerifyModelForDeconstructionLocal(model, x2, x2Ref); // extra check on var var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x12Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void ForWithVarDeconstructInitializersCanParse() { string source = @" using System; class C { static void Main() { int x3; for (var (x1, x2) = (1, 2), x3 = 3; true; ) { Console.WriteLine(x1); Console.WriteLine(x2); Console.WriteLine(x3); break; } } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); }; var comp = CompileAndVerify(source, expectedOutput: @"1 2 3", sourceSymbolValidator: validator); comp.VerifyDiagnostics( // this is permitted now, as it is just an assignment expression ); } [Fact] public void ForWithActualVarType() { string source = @" class C { static void Main() { for ((int x1, var x2) = (1, new var()); x1 < 2; x1++) { System.Console.WriteLine(x1 + "" "" + x2); } } } class var { public override string ToString() { return ""var""; } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 3); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); // extra checks on x1 var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); // extra checks on x2 var x2Type = GetTypeSyntax(x2); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind); Assert.Equal("var", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString()); }; var comp = CompileAndVerify(source, expectedOutput: "1 var", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void ForWithTypes() { string source = @" class C { static void Main() { for ((int x1, var x2) = (1, 2); x1 < 2; x1++) { System.Console.WriteLine(x1 + "" "" + x2); } } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 3); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); // extra checks on x1 var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); // extra checks on x2 var x2Type = GetTypeSyntax(x2); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString()); }; var comp = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void ForEachIEnumerableDeclarationWithImplicitVarType() { string source = @" using System.Collections.Generic; class C { static void Main() { foreach (var (x1, x2) in M()) { Print(x1, x2); } } static IEnumerable<(int, int)> M() { yield return (1, 2); } static void Print(object a, object b) { System.Console.WriteLine(a + "" "" + b); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); // extra check on var var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x12Var.Type.ToString()); Assert.Equal("(System.Int32 x1, System.Int32 x2)", model.GetTypeInfo(x12Var).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol // verify deconstruction info var deconstructionForeach = tree.GetRoot().DescendantNodes().OfType<ForEachVariableStatementSyntax>().Single(); var deconstructionInfo = model.GetDeconstructionInfo(deconstructionForeach); Assert.Null(deconstructionInfo.Method); Assert.Null(deconstructionInfo.Conversion); var nested = deconstructionInfo.Nested; Assert.Equal(2, nested.Length); Assert.Null(nested[0].Method); Assert.Equal(ConversionKind.Identity, nested[0].Conversion.Value.Kind); Assert.Empty(nested[0].Nested); Assert.Null(nested[1].Method); Assert.Equal(ConversionKind.Identity, nested[1].Conversion.Value.Kind); Assert.Empty(nested[1].Nested); }; var comp = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); var comp7_1 = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1); comp7_1.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 70 (0x46) .maxstack 2 .locals init (System.Collections.Generic.IEnumerator<System.ValueTuple<int, int>> V_0, int V_1, //x1 int V_2) //x2 IL_0000: call ""System.Collections.Generic.IEnumerable<System.ValueTuple<int, int>> C.M()"" IL_0005: callvirt ""System.Collections.Generic.IEnumerator<System.ValueTuple<int, int>> System.Collections.Generic.IEnumerable<System.ValueTuple<int, int>>.GetEnumerator()"" IL_000a: stloc.0 .try { IL_000b: br.s IL_0031 IL_000d: ldloc.0 IL_000e: callvirt ""System.ValueTuple<int, int> System.Collections.Generic.IEnumerator<System.ValueTuple<int, int>>.Current.get"" IL_0013: dup IL_0014: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0019: stloc.1 IL_001a: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_001f: stloc.2 IL_0020: ldloc.1 IL_0021: box ""int"" IL_0026: ldloc.2 IL_0027: box ""int"" IL_002c: call ""void C.Print(object, object)"" IL_0031: ldloc.0 IL_0032: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_0037: brtrue.s IL_000d IL_0039: leave.s IL_0045 } finally { IL_003b: ldloc.0 IL_003c: brfalse.s IL_0044 IL_003e: ldloc.0 IL_003f: callvirt ""void System.IDisposable.Dispose()"" IL_0044: endfinally } IL_0045: ret }"); } [Fact] public void ForEachSZArrayDeclarationWithImplicitVarType() { string source = @" class C { static void Main() { foreach (var (x1, x2) in M()) { System.Console.Write(x1 + "" "" + x2 + "" - ""); } } static (int, int)[] M() { return new[] { (1, 2), (3, 4) }; } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); var symbol = model.GetDeclaredSymbol(x1); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); // extra check on var var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x12Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 2 - 3 4 -", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 75 (0x4b) .maxstack 4 .locals init (System.ValueTuple<int, int>[] V_0, int V_1, int V_2, //x1 int V_3) //x2 IL_0000: call ""System.ValueTuple<int, int>[] C.M()"" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: stloc.1 IL_0008: br.s IL_0044 IL_000a: ldloc.0 IL_000b: ldloc.1 IL_000c: ldelem ""System.ValueTuple<int, int>"" IL_0011: dup IL_0012: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0017: stloc.2 IL_0018: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_001d: stloc.3 IL_001e: ldloca.s V_2 IL_0020: call ""string int.ToString()"" IL_0025: ldstr "" "" IL_002a: ldloca.s V_3 IL_002c: call ""string int.ToString()"" IL_0031: ldstr "" - "" IL_0036: call ""string string.Concat(string, string, string, string)"" IL_003b: call ""void System.Console.Write(string)"" IL_0040: ldloc.1 IL_0041: ldc.i4.1 IL_0042: add IL_0043: stloc.1 IL_0044: ldloc.1 IL_0045: ldloc.0 IL_0046: ldlen IL_0047: conv.i4 IL_0048: blt.s IL_000a IL_004a: ret }"); } [Fact] public void ForEachMDArrayDeclarationWithImplicitVarType() { string source = @" class C { static void Main() { foreach (var (x1, x2) in M()) { Print(x1, x2); } } static (int, int)[,] M() { return new (int, int)[2, 2] { { (1, 2), (3, 4) }, { (5, 6), (7, 8) } }; } static void Print(object a, object b) { System.Console.Write(a + "" "" + b + "" - ""); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); // extra check on var var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x12Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 2 - 3 4 - 5 6 - 7 8 -", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 106 (0x6a) .maxstack 3 .locals init (System.ValueTuple<int, int>[,] V_0, int V_1, int V_2, int V_3, int V_4, int V_5, //x1 int V_6) //x2 IL_0000: call ""System.ValueTuple<int, int>[,] C.M()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: callvirt ""int System.Array.GetUpperBound(int)"" IL_000d: stloc.1 IL_000e: ldloc.0 IL_000f: ldc.i4.1 IL_0010: callvirt ""int System.Array.GetUpperBound(int)"" IL_0015: stloc.2 IL_0016: ldloc.0 IL_0017: ldc.i4.0 IL_0018: callvirt ""int System.Array.GetLowerBound(int)"" IL_001d: stloc.3 IL_001e: br.s IL_0065 IL_0020: ldloc.0 IL_0021: ldc.i4.1 IL_0022: callvirt ""int System.Array.GetLowerBound(int)"" IL_0027: stloc.s V_4 IL_0029: br.s IL_005c IL_002b: ldloc.0 IL_002c: ldloc.3 IL_002d: ldloc.s V_4 IL_002f: call ""(int, int)[*,*].Get"" IL_0034: dup IL_0035: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_003a: stloc.s V_5 IL_003c: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0041: stloc.s V_6 IL_0043: ldloc.s V_5 IL_0045: box ""int"" IL_004a: ldloc.s V_6 IL_004c: box ""int"" IL_0051: call ""void C.Print(object, object)"" IL_0056: ldloc.s V_4 IL_0058: ldc.i4.1 IL_0059: add IL_005a: stloc.s V_4 IL_005c: ldloc.s V_4 IL_005e: ldloc.2 IL_005f: ble.s IL_002b IL_0061: ldloc.3 IL_0062: ldc.i4.1 IL_0063: add IL_0064: stloc.3 IL_0065: ldloc.3 IL_0066: ldloc.1 IL_0067: ble.s IL_0020 IL_0069: ret }"); } [Fact] public void ForEachStringDeclarationWithImplicitVarType() { string source = @" class C { static void Main() { foreach (var (x1, x2) in M()) { Print(x1, x2); } } static string M() { return ""123""; } static void Print(object a, object b) { System.Console.Write(a + "" "" + b + "" - ""); } } static class Extension { public static void Deconstruct(this char value, out int item1, out int item2) { item1 = item2 = System.Int32.Parse(value.ToString()); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); // extra check on var var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x12Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 1 - 2 2 - 3 3 - ", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 60 (0x3c) .maxstack 3 .locals init (string V_0, int V_1, int V_2, //x2 int V_3, int V_4) IL_0000: call ""string C.M()"" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: stloc.1 IL_0008: br.s IL_0032 IL_000a: ldloc.0 IL_000b: ldloc.1 IL_000c: callvirt ""char string.this[int].get"" IL_0011: ldloca.s V_3 IL_0013: ldloca.s V_4 IL_0015: call ""void Extension.Deconstruct(char, out int, out int)"" IL_001a: ldloc.3 IL_001b: ldloc.s V_4 IL_001d: stloc.2 IL_001e: box ""int"" IL_0023: ldloc.2 IL_0024: box ""int"" IL_0029: call ""void C.Print(object, object)"" IL_002e: ldloc.1 IL_002f: ldc.i4.1 IL_0030: add IL_0031: stloc.1 IL_0032: ldloc.1 IL_0033: ldloc.0 IL_0034: callvirt ""int string.Length.get"" IL_0039: blt.s IL_000a IL_003b: ret }"); } [Fact] [WorkItem(22495, "https://github.com/dotnet/roslyn/issues/22495")] public void ForEachCollectionSymbol() { string source = @" using System.Collections.Generic; class Deconstructable { void M(IEnumerable<Deconstructable> x) { foreach (var (y1, y2) in x) { } } void Deconstruct(out int i, out int j) { i = 0; j = 0; } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var collection = tree.GetRoot().DescendantNodes().OfType<ForEachVariableStatementSyntax>().Single().Expression; Assert.Equal("x", collection.ToString()); var symbol = model.GetSymbolInfo(collection).Symbol; Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal("x", symbol.Name); Assert.Equal("System.Collections.Generic.IEnumerable<Deconstructable> x", symbol.ToTestDisplayString()); } [Fact] public void ForEachIEnumerableDeclarationWithNesting() { string source = @" using System.Collections.Generic; class C { static void Main() { foreach ((int x1, var (x2, x3), (int x4, int x5)) in M()) { System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4 + "" "" + x5 + "" - ""); } } static IEnumerable<(int, (int, int), (int, int))> M() { yield return (1, (2, 3), (4, 5)); yield return (6, (7, 8), (9, 10)); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionForeach(model, x3, x3Ref); var x4 = GetDeconstructionVariable(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForDeconstructionForeach(model, x4, x4Ref); var x5 = GetDeconstructionVariable(tree, "x5"); var x5Ref = GetReference(tree, "x5"); VerifyModelForDeconstructionForeach(model, x5, x5Ref); // extra check on var var x23Var = (DeclarationExpressionSyntax)x2.Parent.Parent; Assert.Equal("var", x23Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x23Var.Type).Symbol); // The var in `var (x2, x3)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4 5 - 6 7 8 9 10 -", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void ForEachSZArrayDeclarationWithNesting() { string source = @" class C { static void Main() { foreach ((int x1, var (x2, x3), (int x4, int x5)) in M()) { System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4 + "" "" + x5 + "" - ""); } } static (int, (int, int), (int, int))[] M() { return new[] { (1, (2, 3), (4, 5)), (6, (7, 8), (9, 10)) }; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4 5 - 6 7 8 9 10 -"); comp.VerifyDiagnostics(); } [Fact] public void ForEachMDArrayDeclarationWithNesting() { string source = @" class C { static void Main() { foreach ((int x1, var (x2, x3), (int x4, int x5)) in M()) { System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4 + "" "" + x5 + "" - ""); } } static (int, (int, int), (int, int))[,] M() { return new(int, (int, int), (int, int))[1, 2] { { (1, (2, 3), (4, 5)), (6, (7, 8), (9, 10)) } }; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4 5 - 6 7 8 9 10 -"); comp.VerifyDiagnostics(); } [Fact] public void ForEachStringDeclarationWithNesting() { string source = @" class C { static void Main() { foreach ((int x1, var (x2, x3)) in M()) { System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" - ""); } } static string M() { return ""12""; } } static class Extension { public static void Deconstruct(this char value, out int item1, out (int, int) item2) { item1 = System.Int32.Parse(value.ToString()); item2 = (item1, item1); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 1 1 - 2 2 2 - "); comp.VerifyDiagnostics(); } [Fact] public void DeconstructExtensionOnInterface() { string source = @" public interface Interface { } class C : Interface { static void Main() { var (x, y) = new C(); System.Console.Write($""{x} {y}""); } } static class Extension { public static void Deconstruct(this Interface value, out int item1, out string item2) { item1 = 42; item2 = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "42 hello"); comp.VerifyDiagnostics(); } [Fact] public void ForEachIEnumerableDeclarationWithDeconstruct() { string source = @" using System.Collections.Generic; class C { static void Main() { foreach ((long x1, var (x2, x3)) in M()) { Print(x1, x2, x3); } } static IEnumerable<Pair<int, Pair<int, int>>> M() { yield return Pair.Create(1, Pair.Create(2, 3)); yield return Pair.Create(4, Pair.Create(5, 6)); } static void Print(object a, object b, object c) { System.Console.WriteLine(a + "" "" + b + "" "" + c); } } " + commonSource; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionForeach(model, x3, x3Ref); // extra check on var var x23Var = (DeclarationExpressionSyntax)x2.Parent.Parent; Assert.Equal("var", x23Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x23Var.Type).Symbol); // The var in `var (x2, x3)` has no symbol }; string expected = @"Deconstructing (1, (2, 3)) Deconstructing (2, 3) 1 2 3 Deconstructing (4, (5, 6)) Deconstructing (5, 6) 4 5 6"; var comp = CompileAndVerify(source, expectedOutput: expected, sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 90 (0x5a) .maxstack 3 .locals init (System.Collections.Generic.IEnumerator<Pair<int, Pair<int, int>>> V_0, int V_1, //x2 int V_2, //x3 int V_3, Pair<int, int> V_4, int V_5, int V_6) IL_0000: call ""System.Collections.Generic.IEnumerable<Pair<int, Pair<int, int>>> C.M()"" IL_0005: callvirt ""System.Collections.Generic.IEnumerator<Pair<int, Pair<int, int>>> System.Collections.Generic.IEnumerable<Pair<int, Pair<int, int>>>.GetEnumerator()"" IL_000a: stloc.0 .try { IL_000b: br.s IL_0045 IL_000d: ldloc.0 IL_000e: callvirt ""Pair<int, Pair<int, int>> System.Collections.Generic.IEnumerator<Pair<int, Pair<int, int>>>.Current.get"" IL_0013: ldloca.s V_3 IL_0015: ldloca.s V_4 IL_0017: callvirt ""void Pair<int, Pair<int, int>>.Deconstruct(out int, out Pair<int, int>)"" IL_001c: ldloc.s V_4 IL_001e: ldloca.s V_5 IL_0020: ldloca.s V_6 IL_0022: callvirt ""void Pair<int, int>.Deconstruct(out int, out int)"" IL_0027: ldloc.3 IL_0028: conv.i8 IL_0029: ldloc.s V_5 IL_002b: stloc.1 IL_002c: ldloc.s V_6 IL_002e: stloc.2 IL_002f: box ""long"" IL_0034: ldloc.1 IL_0035: box ""int"" IL_003a: ldloc.2 IL_003b: box ""int"" IL_0040: call ""void C.Print(object, object, object)"" IL_0045: ldloc.0 IL_0046: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_004b: brtrue.s IL_000d IL_004d: leave.s IL_0059 } finally { IL_004f: ldloc.0 IL_0050: brfalse.s IL_0058 IL_0052: ldloc.0 IL_0053: callvirt ""void System.IDisposable.Dispose()"" IL_0058: endfinally } IL_0059: ret } "); } [Fact] public void ForEachSZArrayDeclarationWithDeconstruct() { string source = @" class C { static void Main() { foreach ((int x1, var (x2, x3)) in M()) { System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } static Pair<int, Pair<int, int>>[] M() { return new[] { Pair.Create(1, Pair.Create(2, 3)), Pair.Create(4, Pair.Create(5, 6)) }; } } " + commonSource; string expected = @"Deconstructing (1, (2, 3)) Deconstructing (2, 3) 1 2 3 Deconstructing (4, (5, 6)) Deconstructing (5, 6) 4 5 6"; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void ForEachMDArrayDeclarationWithDeconstruct() { string source = @" class C { static void Main() { foreach ((int x1, var (x2, x3)) in M()) { System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } static Pair<int, Pair<int, int>>[,] M() { return new Pair<int, Pair<int, int>> [1, 2] { { Pair.Create(1, Pair.Create(2, 3)), Pair.Create(4, Pair.Create(5, 6)) } }; } } " + commonSource; string expected = @"Deconstructing (1, (2, 3)) Deconstructing (2, 3) 1 2 3 Deconstructing (4, (5, 6)) Deconstructing (5, 6) 4 5 6"; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void ForEachWithExpressionBody() { string source = @" class C { static void Main() { foreach (var (x1, x2) in new[] { (1, 2), (3, 4) }) System.Console.Write(x1 + "" "" + x2 + "" - ""); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2 - 3 4 -"); comp.VerifyDiagnostics(); } [Fact] public void ForEachCreatesNewVariables() { string source = @" class C { static void Main() { var lambdas = new System.Action[2]; int index = 0; foreach (var (x1, x2) in M()) { lambdas[index] = () => { System.Console.Write(x1 + "" ""); }; index++; } lambdas[0](); lambdas[1](); } static (int, int)[] M() { return new[] { (0, 0), (10, 10) }; } } "; var comp = CompileAndVerify(source, expectedOutput: "0 10 "); comp.VerifyDiagnostics(); } [Fact] public void TupleDeconstructionIntoDynamicArrayIndexer() { string source = @" class C { static void Main() { dynamic x = new string[] { """", """" }; M(x); System.Console.WriteLine($""{x[0]} {x[1]}""); } static void M(dynamic x) { (x[0], x[1]) = (""hello"", ""world""); } } "; var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void IntTupleDeconstructionIntoDynamicArrayIndexer() { string source = @" class C { static void Main() { dynamic x = new int[] { 1, 2 }; M(x); System.Console.WriteLine($""{x[0]} {x[1]}""); } static void M(dynamic x) { (x[0], x[1]) = (3, 4); } } "; var comp = CompileAndVerify(source, expectedOutput: "3 4", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DeconstructionIntoDynamicArrayIndexer() { string source = @" class C { static void Main() { dynamic x = new string[] { """", """" }; M(x); System.Console.WriteLine($""{x[0]} {x[1]}""); } static void M(dynamic x) { (x[0], x[1]) = new C(); } public void Deconstruct(out string a, out string b) { a = ""hello""; b = ""world""; } } "; var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void TupleDeconstructionIntoDynamicArray() { string source = @" class C { static void Main() { dynamic[] x = new string[] { """", """" }; M(x); System.Console.WriteLine($""{x[0]} {x[1]}""); } static void M(dynamic[] x) { (x[0], x[1]) = (""hello"", ""world""); } } "; var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DeconstructionIntoDynamicArray() { string source = @" class C { static void Main() { dynamic[] x = new string[] { """", """" }; M(x); System.Console.WriteLine($""{x[0]} {x[1]}""); } static void M(dynamic[] x) { (x[0], x[1]) = new C(); } public void Deconstruct(out string a, out string b) { a = ""hello""; b = ""world""; } } "; var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DeconstructionIntoDynamicMember() { string source = @" class C { static void Main() { dynamic x = System.ValueTuple.Create(1, 2); (x.Item1, x.Item2) = new C(); System.Console.WriteLine($""{x.Item1} {x.Item2}""); } public void Deconstruct(out int a, out int b) { a = 3; b = 4; } } "; var comp = CompileAndVerify(source, expectedOutput: "3 4", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void FieldAndLocalWithSameName() { string source = @" class C { public int x = 3; static void Main() { new C().M(); } void M() { var (x, y) = (1, 2); System.Console.Write($""{x} {y} {this.x}""); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2 3"); comp.VerifyDiagnostics(); } [Fact] public void NoGlobalDeconstructionUnlessScript() { string source = @" class C { var (x, y) = (1, 2); } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,11): error CS1001: Identifier expected // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_IdentifierExpected, ",").WithLocation(4, 11), // (4,14): error CS1001: Identifier expected // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 14), // (4,16): error CS1002: ; expected // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_SemicolonExpected, "=").WithLocation(4, 16), // (4,16): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(4, 16), // (4,19): error CS1031: Type expected // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_TypeExpected, "1").WithLocation(4, 19), // (4,19): error CS8124: Tuple must contain at least two elements. // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_TupleTooFewElements, "1").WithLocation(4, 19), // (4,19): error CS1026: ) expected // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_CloseParenExpected, "1").WithLocation(4, 19), // (4,19): error CS1519: Invalid token '1' in class, record, struct, or interface member declaration // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "1").WithArguments("1").WithLocation(4, 19), // (4,5): error CS1520: Method must have a return type // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_MemberNeedsType, "var").WithLocation(4, 5), // (4,5): error CS0501: 'C.C(x, y)' must declare a body because it is not marked abstract, extern, or partial // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "var").WithArguments("C.C(x, y)").WithLocation(4, 5), // (4,10): error CS0246: The type or namespace name 'x' could not be found (are you missing a using directive or an assembly reference?) // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "x").WithArguments("x").WithLocation(4, 10), // (4,13): error CS0246: The type or namespace name 'y' could not be found (are you missing a using directive or an assembly reference?) // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "y").WithArguments("y").WithLocation(4, 13) ); var nodes = comp.SyntaxTrees[0].GetCompilationUnitRoot().DescendantNodesAndSelf(); Assert.False(nodes.Any(n => n.Kind() == SyntaxKind.SimpleAssignmentExpression)); } [Fact] public void SimpleDeconstructionInScript() { var source = @" using alias = System.Int32; (string x, alias y) = (""hello"", 42); System.Console.Write($""{x} {y}""); "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xSymbol = model.GetDeclaredSymbol(x); var xRef = GetReference(tree, "x"); Assert.Equal("System.String Script.x", xSymbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x, xRef); var y = GetDeconstructionVariable(tree, "y"); var ySymbol = model.GetDeclaredSymbol(y); var yRef = GetReference(tree, "y"); Assert.Equal("System.Int32 Script.y", ySymbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, y, yRef); // extra checks on x var xType = GetTypeSyntax(x); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(xType).Symbol.Kind); Assert.Equal("string", model.GetSymbolInfo(xType).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(xType)); // extra checks on y var yType = GetTypeSyntax(y); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(yType).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(yType).Symbol.ToDisplayString()); Assert.Equal("alias=System.Int32", model.GetAliasInfo(yType).ToTestDisplayString()); }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42", sourceSymbolValidator: validator); verifier.VerifyIL("<<Initialize>>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 129 (0x81) .maxstack 3 .locals init (int V_0, object V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""int <<Initialize>>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldarg.0 IL_0008: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_000d: ldstr ""hello"" IL_0012: stfld ""string x"" IL_0017: ldarg.0 IL_0018: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_001d: ldc.i4.s 42 IL_001f: stfld ""int y"" IL_0024: ldstr ""{0} {1}"" IL_0029: ldarg.0 IL_002a: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_002f: ldfld ""string x"" IL_0034: ldarg.0 IL_0035: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_003a: ldfld ""int y"" IL_003f: box ""int"" IL_0044: call ""string string.Format(string, object, object)"" IL_0049: call ""void System.Console.Write(string)"" IL_004e: nop IL_004f: ldnull IL_0050: stloc.1 IL_0051: leave.s IL_006b } catch System.Exception { IL_0053: stloc.2 IL_0054: ldarg.0 IL_0055: ldc.i4.s -2 IL_0057: stfld ""int <<Initialize>>d__0.<>1__state"" IL_005c: ldarg.0 IL_005d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0062: ldloc.2 IL_0063: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)"" IL_0068: nop IL_0069: leave.s IL_0080 } IL_006b: ldarg.0 IL_006c: ldc.i4.s -2 IL_006e: stfld ""int <<Initialize>>d__0.<>1__state"" IL_0073: ldarg.0 IL_0074: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0079: ldloc.1 IL_007a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)"" IL_007f: nop IL_0080: ret }"); } [Fact] public void GlobalDeconstructionOutsideScript() { var source = @" (string x, int y) = (""hello"", 42); System.Console.Write(x); System.Console.Write(y); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var nodes = comp.SyntaxTrees[0].GetCompilationUnitRoot().DescendantNodesAndSelf(); Assert.True(nodes.Any(n => n.Kind() == SyntaxKind.SimpleAssignmentExpression)); CompileAndVerify(comp, expectedOutput: "hello42"); } [Fact] public void NestedDeconstructionInScript() { var source = @" (string x, (int y, int z)) = (""hello"", (42, 43)); System.Console.Write($""{x} {y} {z}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 43"); } [Fact] public void VarDeconstructionInScript() { var source = @" (var x, var y) = (""hello"", 42); System.Console.Write($""{x} {y}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42"); } [Fact] public void NestedVarDeconstructionInScript() { var source = @" (var x1, var (x2, x3)) = (""hello"", (42, 43)); System.Console.Write($""{x1} {x2} {x3}""); "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("System.String Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Symbol = model.GetDeclaredSymbol(x2); var x2Ref = GetReference(tree, "x2"); Assert.Equal("System.Int32 Script.x2", x2Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x2, x2Ref); // extra checks on x1's var var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("string", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(x1Type)); // extra check on x2 and x3's var var x23Var = (DeclarationExpressionSyntax)x2.Parent.Parent; Assert.Equal("var", x23Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x23Var.Type).Symbol); // The var in `var (x2, x3)` has no symbol }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 43", sourceSymbolValidator: validator); } [Fact] public void EvaluationOrderForDeconstructionInScript() { var source = @" (int, int) M(out int x) { x = 1; return (2, 3); } var (x2, x3) = M(out var x1); System.Console.Write($""{x1} {x2} {x3}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "1 2 3"); verifier.VerifyIL("<<Initialize>>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 178 (0xb2) .maxstack 4 .locals init (int V_0, object V_1, System.ValueTuple<int, int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int <<Initialize>>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldarg.0 IL_0008: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_000d: ldarg.0 IL_000e: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_0013: ldflda ""int x1"" IL_0018: call ""System.ValueTuple<int, int> M(out int)"" IL_001d: stloc.2 IL_001e: ldarg.0 IL_001f: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_0024: ldloc.2 IL_0025: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_002a: stfld ""int x2"" IL_002f: ldarg.0 IL_0030: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_0035: ldloc.2 IL_0036: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_003b: stfld ""int x3"" IL_0040: ldstr ""{0} {1} {2}"" IL_0045: ldarg.0 IL_0046: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_004b: ldfld ""int x1"" IL_0050: box ""int"" IL_0055: ldarg.0 IL_0056: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_005b: ldfld ""int x2"" IL_0060: box ""int"" IL_0065: ldarg.0 IL_0066: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_006b: ldfld ""int x3"" IL_0070: box ""int"" IL_0075: call ""string string.Format(string, object, object, object)"" IL_007a: call ""void System.Console.Write(string)"" IL_007f: nop IL_0080: ldnull IL_0081: stloc.1 IL_0082: leave.s IL_009c } catch System.Exception { IL_0084: stloc.3 IL_0085: ldarg.0 IL_0086: ldc.i4.s -2 IL_0088: stfld ""int <<Initialize>>d__0.<>1__state"" IL_008d: ldarg.0 IL_008e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0093: ldloc.3 IL_0094: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)"" IL_0099: nop IL_009a: leave.s IL_00b1 } IL_009c: ldarg.0 IL_009d: ldc.i4.s -2 IL_009f: stfld ""int <<Initialize>>d__0.<>1__state"" IL_00a4: ldarg.0 IL_00a5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_00aa: ldloc.1 IL_00ab: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)"" IL_00b0: nop IL_00b1: ret } "); } [Fact] public void DeconstructionForEachInScript() { var source = @" foreach ((string x1, var (x2, x3)) in new[] { (""hello"", (42, ""world"")) }) { System.Console.Write($""{x1} {x2} {x3}""); } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); Assert.Equal("System.String x1", x1Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, x1Symbol.Kind); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Symbol = model.GetDeclaredSymbol(x2); Assert.Equal("System.Int32 x2", x2Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, x2Symbol.Kind); }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 world", sourceSymbolValidator: validator); } [Fact] public void DeconstructionInForLoopInScript() { var source = @" for ((string x1, var (x2, x3)) = (""hello"", (42, ""world"")); ; ) { System.Console.Write($""{x1} {x2} {x3}""); break; } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); Assert.Equal("System.String x1", x1Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, x1Symbol.Kind); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Symbol = model.GetDeclaredSymbol(x2); Assert.Equal("System.Int32 x2", x2Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, x2Symbol.Kind); }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 world", sourceSymbolValidator: validator); } [Fact] public void DeconstructionInCSharp6Script() { var source = @" var (x, y) = (1, 2); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp6), options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (2,5): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(x, y)").WithArguments("tuples", "7.0").WithLocation(2, 5), // (2,14): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7 or greater. // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(1, 2)").WithArguments("tuples", "7.0").WithLocation(2, 14) ); } [Fact] public void InvalidDeconstructionInScript() { var source = @" int (x, y) = (1, 2); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (2,5): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'. // int (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x, y)").WithLocation(2, 5) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xSymbol = model.GetDeclaredSymbol(x); Assert.Equal("System.Int32 Script.x", xSymbol.ToTestDisplayString()); var xType = ((IFieldSymbol)xSymbol).Type; Assert.False(xType.IsErrorType()); Assert.Equal("System.Int32", xType.ToTestDisplayString()); var y = GetDeconstructionVariable(tree, "y"); var ySymbol = model.GetDeclaredSymbol(y); Assert.Equal("System.Int32 Script.y", ySymbol.ToTestDisplayString()); var yType = ((IFieldSymbol)ySymbol).Type; Assert.False(yType.IsErrorType()); Assert.Equal("System.Int32", yType.ToTestDisplayString()); } [Fact] public void InvalidDeconstructionInScript_2() { var source = @" (int (x, y), int z) = ((1, 2), 3); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (2,6): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'. // (int (x, y), int z) = ((1, 2), 3); Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x, y)").WithLocation(2, 6) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xSymbol = model.GetDeclaredSymbol(x); Assert.Equal("System.Int32 Script.x", xSymbol.ToTestDisplayString()); var xType = ((IFieldSymbol)xSymbol).Type; Assert.False(xType.IsErrorType()); Assert.Equal("System.Int32", xType.ToTestDisplayString()); var y = GetDeconstructionVariable(tree, "y"); var ySymbol = model.GetDeclaredSymbol(y); Assert.Equal("System.Int32 Script.y", ySymbol.ToTestDisplayString()); var yType = ((IFieldSymbol)ySymbol).Type; Assert.False(yType.IsErrorType()); Assert.Equal("System.Int32", yType.ToTestDisplayString()); } [Fact] public void NameConflictInDeconstructionInScript() { var source = @" int x1; var (x1, x2) = (1, 2); System.Console.Write(x1); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (3,6): error CS0102: The type 'Script' already contains a definition for 'x1' // var (x1, x2) = (1, 2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x1").WithArguments("Script", "x1").WithLocation(3, 6), // (4,22): error CS0229: Ambiguity between 'x1' and 'x1' // System.Console.Write(x1); Diagnostic(ErrorCode.ERR_AmbigMember, "x1").WithArguments("x1", "x1").WithLocation(4, 22) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var firstX1 = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "x1").Single(); var firstX1Symbol = model.GetDeclaredSymbol(firstX1); Assert.Equal("System.Int32 Script.x1", firstX1Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, firstX1Symbol.Kind); var secondX1 = GetDeconstructionVariable(tree, "x1"); var secondX1Symbol = model.GetDeclaredSymbol(secondX1); Assert.Equal("System.Int32 Script.x1", secondX1Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, secondX1Symbol.Kind); Assert.NotEqual(firstX1Symbol, secondX1Symbol); } [Fact] public void NameConflictInDeconstructionInScript2() { var source = @" var (x, y) = (1, 2); var (z, y) = (1, 2); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (3,9): error CS0102: The type 'Script' already contains a definition for 'y' // var (z, y) = (1, 2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "y").WithArguments("Script", "y").WithLocation(3, 9) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var firstY = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "y").First(); var firstYSymbol = model.GetDeclaredSymbol(firstY); Assert.Equal("System.Int32 Script.y", firstYSymbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, firstYSymbol.Kind); var secondY = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "y").ElementAt(1); var secondYSymbol = model.GetDeclaredSymbol(secondY); Assert.Equal("System.Int32 Script.y", secondYSymbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, secondYSymbol.Kind); Assert.NotEqual(firstYSymbol, secondYSymbol); } [Fact] public void NameConflictInDeconstructionInScript3() { var source = @" var (x, (y, x)) = (1, (2, ""hello"")); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (2,13): error CS0102: The type 'Script' already contains a definition for 'x' // var (x, (y, x)) = (1, (2, "hello")); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x").WithArguments("Script", "x").WithLocation(2, 13) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var firstX = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "x").First(); var firstXSymbol = model.GetDeclaredSymbol(firstX); Assert.Equal("System.Int32 Script.x", firstXSymbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, firstXSymbol.Kind); var secondX = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "x").ElementAt(1); var secondXSymbol = model.GetDeclaredSymbol(secondX); Assert.Equal("System.String Script.x", secondXSymbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, secondXSymbol.Kind); Assert.NotEqual(firstXSymbol, secondXSymbol); } [Fact] public void UnassignedUsedInDeconstructionInScript() { var source = @" System.Console.Write(x); var (x, y) = (1, 2); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "0"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xSymbol = model.GetDeclaredSymbol(x); var xRef = GetReference(tree, "x"); Assert.Equal("System.Int32 Script.x", xSymbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x, xRef); var xType = ((IFieldSymbol)xSymbol).Type; Assert.False(xType.IsErrorType()); Assert.Equal("System.Int32", xType.ToTestDisplayString()); } [Fact] public void FailedInferenceInDeconstructionInScript() { var source = @" var (x, y) = (1, null); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.GetDeclarationDiagnostics().Verify( // (2,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = (1, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(2, 6), // (2,9): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = (1, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(2, 9) ); comp.VerifyDiagnostics( // (2,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = (1, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(2, 6), // (2,9): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = (1, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(2, 9) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xSymbol = model.GetDeclaredSymbol(x); Assert.Equal("var Script.x", xSymbol.ToTestDisplayString()); var xType = xSymbol.GetSymbol<FieldSymbol>().TypeWithAnnotations; Assert.True(xType.Type.IsErrorType()); Assert.Equal("var", xType.ToTestDisplayString()); var xTypeISymbol = xType.Type.GetPublicSymbol(); Assert.Equal(SymbolKind.ErrorType, xTypeISymbol.Kind); var y = GetDeconstructionVariable(tree, "y"); var ySymbol = model.GetDeclaredSymbol(y); Assert.Equal("var Script.y", ySymbol.ToTestDisplayString()); var yType = ((IFieldSymbol)ySymbol).Type; Assert.True(yType.IsErrorType()); Assert.Equal("var", yType.ToTestDisplayString()); } [Fact] public void FailedCircularInferenceInDeconstructionInScript() { var source = @" var (x1, x2) = (x2, x1); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.GetDeclarationDiagnostics().Verify( // (2,10): error CS7019: Type of 'x2' cannot be inferred since its initializer directly or indirectly refers to the definition. // var (x1, x2) = (x2, x1); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x2").WithArguments("x2").WithLocation(2, 10), // (2,6): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // var (x1, x2) = (x2, x1); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 6) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("var Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x1Type = ((IFieldSymbol)x1Symbol).Type; Assert.True(x1Type.IsErrorType()); Assert.Equal("var", x1Type.Name); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Symbol = model.GetDeclaredSymbol(x2); var x2Ref = GetReference(tree, "x2"); Assert.Equal("var Script.x2", x2Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x2, x2Ref); var x2Type = ((IFieldSymbol)x2Symbol).Type; Assert.True(x2Type.IsErrorType()); Assert.Equal("var", x2Type.Name); } [Fact] public void FailedCircularInferenceInDeconstructionInScript2() { var source = @" var (x1, x2) = (y1, y2); var (y1, y2) = (x1, x2); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.GetDeclarationDiagnostics().Verify( // (3,6): error CS7019: Type of 'y1' cannot be inferred since its initializer directly or indirectly refers to the definition. // var (y1, y2) = (x1, x2); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "y1").WithArguments("y1").WithLocation(3, 6), // (2,6): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // var (x1, x2) = (y1, y2); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 6), // (2,10): error CS7019: Type of 'x2' cannot be inferred since its initializer directly or indirectly refers to the definition. // var (x1, x2) = (y1, y2); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x2").WithArguments("x2").WithLocation(2, 10) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("var Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x1Type = ((IFieldSymbol)x1Symbol).Type; Assert.True(x1Type.IsErrorType()); Assert.Equal("var", x1Type.Name); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Symbol = model.GetDeclaredSymbol(x2); var x2Ref = GetReference(tree, "x2"); Assert.Equal("var Script.x2", x2Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x2, x2Ref); var x2Type = ((IFieldSymbol)x2Symbol).Type; Assert.True(x2Type.IsErrorType()); Assert.Equal("var", x2Type.Name); } [Fact] public void VarAliasInVarDeconstructionInScript() { var source = @" using var = System.Byte; var (x1, (x2, x3)) = (1, (2, 3)); System.Console.Write($""{x1} {x2} {x3}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (3,5): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'. // var (x1, (x2, x3)) = (1, (2, 3)); Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x1, (x2, x3))").WithLocation(3, 5) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("System.Byte Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Symbol = model.GetDeclaredSymbol(x3); var x3Ref = GetReference(tree, "x3"); Assert.Equal("System.Byte Script.x3", x3Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x3, x3Ref); // extra check on var var x123Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x123Var.Type.ToString()); Assert.Null(model.GetTypeInfo(x123Var.Type).Type); Assert.Null(model.GetSymbolInfo(x123Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol } [Fact] public void VarTypeInVarDeconstructionInScript() { var source = @" class var { public static implicit operator var(int i) { return null; } } var (x1, (x2, x3)) = (1, (2, 3)); System.Console.Write($""{x1} {x2} {x3}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (6,5): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'. // var (x1, (x2, x3)) = (1, (2, 3)); Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x1, (x2, x3))").WithLocation(6, 5) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("Script.var Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Symbol = model.GetDeclaredSymbol(x3); var x3Ref = GetReference(tree, "x3"); Assert.Equal("Script.var Script.x3", x3Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x3, x3Ref); // extra check on var var x123Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x123Var.Type.ToString()); Assert.Null(model.GetTypeInfo(x123Var.Type).Type); Assert.Null(model.GetSymbolInfo(x123Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol } [Fact] public void VarAliasInTypedDeconstructionInScript() { var source = @" using var = System.Byte; (var x1, (var x2, var x3)) = (1, (2, 3)); System.Console.Write($""{x1} {x2} {x3}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1 2 3"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("System.Byte Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Symbol = model.GetDeclaredSymbol(x3); var x3Ref = GetReference(tree, "x3"); Assert.Equal("System.Byte Script.x3", x3Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x3, x3Ref); // extra checks on x1's var var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("byte", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); var x1Alias = model.GetAliasInfo(x1Type); Assert.Equal(SymbolKind.NamedType, x1Alias.Target.Kind); Assert.Equal("byte", x1Alias.Target.ToDisplayString()); // extra checks on x3's var var x3Type = GetTypeSyntax(x3); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x3Type).Symbol.Kind); Assert.Equal("byte", model.GetSymbolInfo(x3Type).Symbol.ToDisplayString()); var x3Alias = model.GetAliasInfo(x3Type); Assert.Equal(SymbolKind.NamedType, x3Alias.Target.Kind); Assert.Equal("byte", x3Alias.Target.ToDisplayString()); } [Fact] public void VarTypeInTypedDeconstructionInScript() { var source = @" class var { public static implicit operator var(int i) { return new var(); } public override string ToString() { return ""var""; } } (var x1, (var x2, var x3)) = (1, (2, 3)); System.Console.Write($""{x1} {x2} {x3}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "var var var"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("Script.var Script.x1", x1Symbol.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x1).Symbol); VerifyModelForDeconstructionField(model, x1, x1Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Symbol = model.GetDeclaredSymbol(x3); var x3Ref = GetReference(tree, "x3"); Assert.Equal("Script.var Script.x3", x3Symbol.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x3).Symbol); VerifyModelForDeconstructionField(model, x3, x3Ref); // extra checks on x1's var var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("var", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(x1Type)); // extra checks on x3's var var x3Type = GetTypeSyntax(x3); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x3Type).Symbol.Kind); Assert.Equal("var", model.GetSymbolInfo(x3Type).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(x3Type)); } [Fact] public void SimpleDiscardWithConversion() { var source = @" class C { static void Main() { (int _, var x) = (new C(1), 1); (var _, var y) = (new C(2), 2); var (_, z) = (new C(3), 3); System.Console.Write($""Output {x} {y} {z}.""); } int _i; public C(int i) { _i = i; } public static implicit operator int(C c) { System.Console.Write($""Converted {c._i}. ""); return 0; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Converted 1. Output 1 2 3."); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetSymbolInfo(discard1).Symbol); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("int _", declaration1.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); var discard2 = GetDiscardDesignations(tree).ElementAt(1); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.Null(model.GetSymbolInfo(discard2).Symbol); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("var _", declaration2.ToString()); Assert.Equal("C", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); var discard3 = GetDiscardDesignations(tree).ElementAt(2); var declaration3 = (DeclarationExpressionSyntax)discard3.Parent.Parent; Assert.Equal("var (_, z)", declaration3.ToString()); Assert.Equal("(C, System.Int32 z)", model.GetTypeInfo(declaration3).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration3).Symbol); } [Fact] public void CannotDeconstructIntoDiscardOfWrongType() { var source = @" class C { static void Main() { (int _, string _) = (""hello"", 42); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,30): error CS0029: Cannot implicitly convert type 'string' to 'int' // (int _, string _) = ("hello", 42); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""hello""").WithArguments("string", "int").WithLocation(6, 30), // (6,39): error CS0029: Cannot implicitly convert type 'int' to 'string' // (int _, string _) = ("hello", 42); Diagnostic(ErrorCode.ERR_NoImplicitConv, "42").WithArguments("int", "string").WithLocation(6, 39) ); } [Fact] public void DiscardFromDeconstructMethod() { var source = @" class C { static void Main() { (var _, string y) = new C(); System.Console.Write(y); } void Deconstruct(out int x, out string y) { x = 42; y = ""hello""; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "hello"); } [Fact] public void ShortDiscardInDeclaration() { var source = @" class C { static void Main() { (_, var x) = (1, 2); System.Console.Write(x); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard = GetDiscardIdentifiers(tree).First(); var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol; Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal("System.Int32", model.GetTypeInfo(discard).Type.ToTestDisplayString()); var isymbol = (ISymbol)symbol; Assert.Equal(SymbolKind.Discard, isymbol.Kind); } [Fact, WorkItem(25829, "https://github.com/dotnet/roslyn/issues/25829")] public void SameTypeDiscardsAreEqual01() { var source = @" class C { static void Main() { (_, _) = (1, 2); _ = 3; M(out _); } static void M(out int x) => x = 1; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discards = GetDiscardIdentifiers(tree).ToArray(); Assert.Equal(4, discards.Length); var symbol0 = (IDiscardSymbol)model.GetSymbolInfo(discards[0]).Symbol; Assert.Equal(symbol0, symbol0); var set = new HashSet<ISymbol>(); foreach (var discard in discards) { var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol; set.Add(symbol); Assert.Equal(SymbolKind.Discard, symbol.Kind); Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal(symbol0, symbol); Assert.Equal(symbol, symbol); Assert.Equal(symbol.GetHashCode(), symbol0.GetHashCode()); // Test to show that reference-unequal discards are equal by type. IDiscardSymbol symbolClone = new DiscardSymbol(TypeWithAnnotations.Create(symbol.Type.GetSymbol())).GetPublicSymbol(); Assert.NotSame(symbol, symbolClone); Assert.Equal(SymbolKind.Discard, symbolClone.Kind); Assert.Equal("int _", symbolClone.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal(symbol.Type, symbolClone.Type); Assert.Equal(symbol0, symbolClone); Assert.Equal(symbol, symbolClone); Assert.Same(symbol.Type, symbolClone.Type); // original symbol for System.Int32 has identity. Assert.Equal(symbol.GetHashCode(), symbolClone.GetHashCode()); } Assert.Equal(1, set.Count); } [Fact, WorkItem(25829, "https://github.com/dotnet/roslyn/issues/25829")] public void SameTypeDiscardsAreEqual02() { var source = @"using System.Collections.Generic; class C { static void Main() { (_, _) = (new List<int>(), new List<int>()); _ = new List<int>(); M(out _); } static void M(out List<int> x) => x = new List<int>(); } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discards = GetDiscardIdentifiers(tree).ToArray(); Assert.Equal(4, discards.Length); var symbol0 = (IDiscardSymbol)model.GetSymbolInfo(discards[0]).Symbol; Assert.Equal(symbol0, symbol0); var set = new HashSet<ISymbol>(); foreach (var discard in discards) { var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol; set.Add(symbol); Assert.Equal(SymbolKind.Discard, symbol.Kind); Assert.Equal("List<int> _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal(symbol0, symbol); Assert.Equal(symbol0.Type, symbol.Type); Assert.Equal(symbol, symbol); Assert.Equal(symbol.GetHashCode(), symbol0.GetHashCode()); if (discard != discards[0]) { // Although it is not part of the compiler's contract, at the moment distinct constructions are distinct Assert.NotSame(symbol.Type, symbol0.Type); Assert.NotSame(symbol, symbol0); } } Assert.Equal(1, set.Count); } [Fact, WorkItem(25829, "https://github.com/dotnet/roslyn/issues/25829")] public void DifferentTypeDiscardsAreNotEqual() { var source = @" class C { static void Main() { (_, _) = (1.0, 2); _ = 3; M(out _); } static void M(out int x) => x = 1; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discards = GetDiscardIdentifiers(tree).ToArray(); Assert.Equal(4, discards.Length); var symbol0 = (IDiscardSymbol)model.GetSymbolInfo(discards[0]).Symbol; var set = new HashSet<ISymbol>(); foreach (var discard in discards) { var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol; Assert.Equal(SymbolKind.Discard, symbol.Kind); set.Add(symbol); if (discard == discards[0]) { Assert.Equal("double _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal(symbol0, symbol); Assert.Equal(symbol0.GetHashCode(), symbol.GetHashCode()); } else { Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.NotEqual(symbol0, symbol); } } Assert.Equal(2, set.Count); } [Fact] public void EscapedUnderscoreInDeclaration() { var source = @" class C { static void Main() { (@_, var x) = (1, 2); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,10): error CS0103: The name '_' does not exist in the current context // (@_, var x) = (1, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "@_").WithArguments("_").WithLocation(6, 10) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); Assert.Empty(GetDiscardIdentifiers(tree)); } [Fact] public void EscapedUnderscoreInDeclarationCSharp9() { var source = @" class C { static void Main() { (@_, var x) = (1, 2); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (@_, var x) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(@_, var x) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(6, 9), // (6,10): error CS0103: The name '_' does not exist in the current context // (@_, var x) = (1, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "@_").WithArguments("_").WithLocation(6, 10) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); Assert.Empty(GetDiscardIdentifiers(tree)); } [Fact] public void UnderscoreLocalInDeconstructDeclaration() { var source = @" class C { static void Main() { int _; (_, var x) = (1, 2); System.Console.Write(_); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1") .VerifyIL("C.Main", @" { // Code size 13 (0xd) .maxstack 1 .locals init (int V_0, //_ int V_1) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: call ""void System.Console.Write(int)"" IL_000b: nop IL_000c: ret }"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard = GetDiscardIdentifiers(tree).First(); Assert.Equal("(_, var x)", discard.Parent.Parent.ToString()); var symbol = (ILocalSymbol)model.GetSymbolInfo(discard).Symbol; Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal("System.Int32", model.GetTypeInfo(discard).Type.ToTestDisplayString()); } [Fact] public void ShortDiscardInDeconstructAssignment() { var source = @" class C { static void Main() { int x; (_, _, x) = (1, 2, 3); System.Console.Write(x); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void DiscardInDeconstructAssignment() { var source = @" class C { static void Main() { int x; (_, x) = (1L, 2); System.Console.Write(x); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardIdentifiers(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Equal("long _", model.GetSymbolInfo(discard1).Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); var tuple1 = (TupleExpressionSyntax)discard1.Parent.Parent; Assert.Equal("(_, x)", tuple1.ToString()); Assert.Equal("(System.Int64, System.Int32 x)", model.GetTypeInfo(tuple1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(tuple1).Symbol); } [Fact] public void DiscardInDeconstructDeclaration() { var source = @" class C { static void Main() { var (_, x) = (1, 2); System.Console.Write(x); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); var tuple1 = (DeclarationExpressionSyntax)discard1.Parent.Parent; Assert.Equal("var (_, x)", tuple1.ToString()); Assert.Equal("(System.Int32, System.Int32 x)", model.GetTypeInfo(tuple1).Type.ToTestDisplayString()); } [Fact] public void UnderscoreLocalInDeconstructAssignment() { var source = @" class C { static void Main() { int x, _; (_, x) = (1, 2); System.Console.Write($""{_} {x}""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1 2"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard = GetDiscardIdentifiers(tree).First(); Assert.Equal("(_, x)", discard.Parent.Parent.ToString()); var symbol = (ILocalSymbol)model.GetSymbolInfo(discard).Symbol; Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } [Fact] public void DiscardInForeach() { var source = @" class C { static void Main() { foreach (var (_, x) in new[] { (1, ""hello"") }) { System.Console.Write(""1 ""); } foreach ((_, (var y, int z)) in new[] { (1, (""hello"", 2)) }) { System.Console.Write(""2""); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1 2"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); DiscardDesignationSyntax discard1 = GetDiscardDesignations(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetTypeInfo(discard1).Type); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent.Parent; Assert.Equal("var (_, x)", declaration1.ToString()); Assert.Null(model.GetTypeInfo(discard1).Type); Assert.Equal("(System.Int32, System.String x)", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); IdentifierNameSyntax discard2 = GetDiscardIdentifiers(tree).First(); Assert.Equal("(_, (var y, int z))", discard2.Parent.Parent.ToString()); Assert.Equal("int _", model.GetSymbolInfo(discard2).Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal("System.Int32", model.GetTypeInfo(discard2).Type.ToTestDisplayString()); var yz = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(2); Assert.Equal("(var y, int z)", yz.ToString()); Assert.Equal("(System.String y, System.Int32 z)", model.GetTypeInfo(yz).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(yz).Symbol); var y = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(1); Assert.Equal("var y", y.ToString()); Assert.Equal("System.String", model.GetTypeInfo(y).Type.ToTestDisplayString()); Assert.Equal("System.String y", model.GetSymbolInfo(y).Symbol.ToTestDisplayString()); } [Fact] public void TwoDiscardsInForeach() { var source = @" class C { static void Main() { foreach ((_, _) in new[] { (1, ""hello"") }) { System.Console.Write(""2""); } } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var refs = GetReferences(tree, "_"); Assert.Equal(2, refs.Count()); model.GetTypeInfo(refs.ElementAt(0)); // Assert.Equal("int", model.GetTypeInfo(refs.ElementAt(0)).Type.ToDisplayString()); model.GetTypeInfo(refs.ElementAt(1)); // Assert.Equal("string", model.GetTypeInfo(refs.ElementAt(1)).Type.ToDisplayString()); var tuple = (TupleExpressionSyntax)refs.ElementAt(0).Parent.Parent; Assert.Equal("(_, _)", tuple.ToString()); Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(tuple).Type.ToTestDisplayString()); }; var comp = CompileAndVerify(source, expectedOutput: @"2", sourceSymbolValidator: validator); comp.VerifyDiagnostics( // this is permitted now, as it is just an assignment expression ); } [Fact] public void UnderscoreLocalDisallowedInForEach() { var source = @" class C { static void Main() { { foreach ((var x, _) in new[] { (1, ""hello"") }) { System.Console.Write(""2 ""); } } { int _; foreach ((var y, _) in new[] { (1, ""hello"") }) { System.Console.Write(""4""); } // error } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (11,30): error CS0029: Cannot implicitly convert type 'string' to 'int' // foreach ((var y, _) in new[] { (1, "hello") }) { System.Console.Write("4"); } // error Diagnostic(ErrorCode.ERR_NoImplicitConv, "_").WithArguments("string", "int").WithLocation(11, 30), // (11,22): error CS8186: A foreach loop must declare its iteration variables. // foreach ((var y, _) in new[] { (1, "hello") }) { System.Console.Write("4"); } // error Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(var y, _)").WithLocation(11, 22), // (10,17): warning CS0168: The variable '_' is declared but never used // int _; Diagnostic(ErrorCode.WRN_UnreferencedVar, "_").WithArguments("_").WithLocation(10, 17) ); } [Fact] public void TwoDiscardsInDeconstructAssignment() { var source = @" class C { static void Main() { (_, _) = (new C(), new C()); } public C() { System.Console.Write(""C""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "CC"); } [Fact] public void VerifyDiscardIL() { var source = @" class C { C() { System.Console.Write(""ctor""); } static int Main() { var (x, _, _) = (1, new C(), 2); return x; } } "; var comp = CompileAndVerify(source, expectedOutput: "ctor"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main()", @" { // Code size 8 (0x8) .maxstack 1 IL_0000: newobj ""C..ctor()"" IL_0005: pop IL_0006: ldc.i4.1 IL_0007: ret }"); } [Fact] public void SingleDiscardInAssignment() { var source = @" class C { static void Main() { _ = M(); } public static int M() { System.Console.Write(""M""); return 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "M"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardIdentifiers(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Equal("System.Int32", model.GetTypeInfo(discard1).Type.ToTestDisplayString()); } [Fact] public void SingleDiscardInAssignmentInCSharp6() { var source = @" class C { static void Error() { _ = 1; } static void Ok() { int _; _ = 1; System.Console.Write(_); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular6); comp.VerifyDiagnostics( // (6,9): error CS8059: Feature 'discards' is not available in C# 6. Please use language version 7.0 or greater. // _ = 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("discards", "7.0").WithLocation(6, 9) ); } [Fact] public void VariousDiscardsInCSharp6() { var source = @" class C { static void M1(out int x) { (_, var _, int _) = (1, 2, 3); var (_, _) = (1, 2); bool b = 3 is int _; switch (3) { case int _: break; } M1(out var _); M1(out int _); M1(out _); x = 2; } static void M2() { const int _ = 3; switch (3) { case _: // not a discard break; } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular6); comp.VerifyDiagnostics( // (6,9): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // (_, var _, int _) = (1, 2, 3); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(_, var _, int _)").WithArguments("tuples", "7.0").WithLocation(6, 9), // (6,10): error CS8059: Feature 'discards' is not available in C# 6. Please use language version 7.0 or greater. // (_, var _, int _) = (1, 2, 3); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("discards", "7.0").WithLocation(6, 10), // (6,29): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // (_, var _, int _) = (1, 2, 3); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(1, 2, 3)").WithArguments("tuples", "7.0").WithLocation(6, 29), // (7,13): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // var (_, _) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(_, _)").WithArguments("tuples", "7.0").WithLocation(7, 13), // (7,22): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // var (_, _) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(1, 2)").WithArguments("tuples", "7.0").WithLocation(7, 22), // (8,18): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // bool b = 3 is int _; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "3 is int _").WithArguments("pattern matching", "7.0").WithLocation(8, 18), // (11,13): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // case int _: Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "case int _:").WithArguments("pattern matching", "7.0").WithLocation(11, 13), // (14,20): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater. // M1(out var _); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("out variable declaration", "7.0").WithLocation(14, 20), // (15,20): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater. // M1(out int _); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("out variable declaration", "7.0").WithLocation(15, 20), // (16,16): error CS8059: Feature 'discards' is not available in C# 6. Please use language version 7.0 or greater. // M1(out _); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("discards", "7.0").WithLocation(16, 16), // (24,18): warning CS8512: The name '_' refers to the constant, not the discard pattern. Use 'var _' to discard the value, or '@_' to refer to a constant by that name. // case _: // not a discard Diagnostic(ErrorCode.WRN_CaseConstantNamedUnderscore, "_").WithLocation(24, 18) ); } [Fact] public void SingleDiscardInAsyncAssignment() { var source = @" class C { async void M() { System.Threading.Tasks.Task.Delay(new System.TimeSpan(0)); // warning _ = System.Threading.Tasks.Task.Delay(new System.TimeSpan(0)); // fire-and-forget await System.Threading.Tasks.Task.Delay(new System.TimeSpan(0)); } } "; var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (6,9): warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call. // System.Threading.Tasks.Task.Delay(new System.TimeSpan(0)); Diagnostic(ErrorCode.WRN_UnobservedAwaitableExpression, "System.Threading.Tasks.Task.Delay(new System.TimeSpan(0))").WithLocation(6, 9) ); } [Fact] public void SingleDiscardInUntypedAssignment() { var source = @" class C { static void Main() { _ = null; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,9): error CS8183: Cannot infer the type of implicitly-typed discard. // _ = null; Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(6, 9) ); } [Fact] public void UnderscoreLocalInAssignment() { var source = @" class C { static void Main() { int _; _ = M(); System.Console.Write(_); } public static int M() { return 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1"); } [Fact] public void DeclareAndUseLocalInDeconstruction() { var source = @" class C { static void Main() { (var x, x) = (1, 2); (y, var y) = (1, 2); } } "; var compCSharp9 = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compCSharp9.VerifyDiagnostics( // (6,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (var x, x) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(var x, x) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(6, 9), // (6,17): error CS0841: Cannot use local variable 'x' before it is declared // (var x, x) = (1, 2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 17), // (7,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (y, var y) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(y, var y) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(7, 9), // (7,10): error CS0841: Cannot use local variable 'y' before it is declared // (y, var y) = (1, 2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y").WithLocation(7, 10) ); var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (6,17): error CS0841: Cannot use local variable 'x' before it is declared // (var x, x) = (1, 2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 17), // (7,10): error CS0841: Cannot use local variable 'y' before it is declared // (y, var y) = (1, 2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y").WithLocation(7, 10) ); } [Fact] public void OutVarAndUsageInDeconstructAssignment() { var source = @" class C { static void Main() { (M(out var x).P, x) = (1, x); System.Console.Write(x); } static C M(out int i) { i = 42; return new C(); } int P { set { System.Console.Write($""Written {value}. ""); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,26): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (M(out var x).P, x) = (1, x); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(6, 26) ); CompileAndVerify(comp, expectedOutput: "Written 1. 42"); } [Fact] public void OutDiscardInDeconstructAssignment() { var source = @" class C { static void Main() { int _; (M(out var _).P, _) = (1, 2); System.Console.Write(_); } static C M(out int i) { i = 42; return new C(); } int P { set { System.Console.Write($""Written {value}. ""); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Written 1. 2"); } [Fact] public void OutDiscardInDeconstructTarget() { var source = @" class C { static void Main() { (x, _) = (M(out var x), 2); System.Console.Write(x); } static int M(out int i) { i = 42; return 3; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,10): error CS0841: Cannot use local variable 'x' before it is declared // (x, _) = (M(out var x), 2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 10) ); } [Fact] public void SimpleDiscardDeconstructInScript() { var source = @" using alias = System.Int32; (string _, alias _) = (""hello"", 42); "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).First(); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("string _", declaration1.ToString()); Assert.Null(model.GetDeclaredSymbol(declaration1)); Assert.Null(model.GetDeclaredSymbol(discard1)); var discard2 = GetDiscardDesignations(tree).ElementAt(1); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("alias _", declaration2.ToString()); Assert.Null(model.GetDeclaredSymbol(declaration2)); Assert.Null(model.GetDeclaredSymbol(discard2)); var tuple = (TupleExpressionSyntax)declaration1.Parent.Parent; Assert.Equal("(string _, alias _)", tuple.ToString()); Assert.Equal("(System.String, System.Int32)", model.GetTypeInfo(tuple).Type.ToTestDisplayString()); }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, sourceSymbolValidator: validator); } [Fact] public void SimpleDiscardDeconstructInScript2() { var source = @" public class C { public C() { System.Console.Write(""ctor""); } public void Deconstruct(out string x, out string y) { x = y = null; } } (string _, string _) = new C(); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "ctor"); } [Fact] public void SingleDiscardInAssignmentInScript() { var source = @" int M() { System.Console.Write(""M""); return 1; } _ = M(); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "M"); } [Fact] public void NestedVarDiscardDeconstructionInScript() { var source = @" (var _, var (_, x3)) = (""hello"", (42, 43)); System.Console.Write($""{x3}""); "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var discard2 = GetDiscardDesignations(tree).ElementAt(1); var nestedDeclaration = (DeclarationExpressionSyntax)discard2.Parent.Parent; Assert.Equal("var (_, x3)", nestedDeclaration.ToString()); Assert.Null(model.GetDeclaredSymbol(nestedDeclaration)); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.Equal("(System.Int32, System.Int32 x3)", model.GetTypeInfo(nestedDeclaration).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(nestedDeclaration).Symbol); var tuple = (TupleExpressionSyntax)discard2.Parent.Parent.Parent.Parent; Assert.Equal("(var _, var (_, x3))", tuple.ToString()); Assert.Equal("(System.String, (System.Int32, System.Int32 x3))", model.GetTypeInfo(tuple).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(tuple).Symbol); }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "43", sourceSymbolValidator: validator); } [Fact] public void VariousDiscardsInForeach() { var source = @" class C { static void Main() { foreach ((var _, int _, _, var (_, _), int x) in new[] { (1L, 2, 3, (""hello"", 5), 6) }) { System.Console.Write(x); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "6"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.True(model.GetSymbolInfo(discard1).IsEmpty); Assert.Null(model.GetTypeInfo(discard1).Type); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("var _", declaration1.ToString()); Assert.Equal("System.Int64", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); var discard2 = GetDiscardDesignations(tree).ElementAt(1); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.True(model.GetSymbolInfo(discard2).IsEmpty); Assert.Null(model.GetTypeInfo(discard2).Type); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("int _", declaration2.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); var discard3 = GetDiscardIdentifiers(tree).First(); Assert.Equal("_", discard3.Parent.ToString()); Assert.Null(model.GetDeclaredSymbol(discard3)); Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString()); Assert.Equal("int _", model.GetSymbolInfo(discard3).Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol; Assert.Equal("System.Int32", discard3Symbol.Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString()); var discard4 = GetDiscardDesignations(tree).ElementAt(2); Assert.Null(model.GetDeclaredSymbol(discard4)); Assert.True(model.GetSymbolInfo(discard4).IsEmpty); Assert.Null(model.GetTypeInfo(discard4).Type); var nestedDeclaration = (DeclarationExpressionSyntax)discard4.Parent.Parent; Assert.Equal("var (_, _)", nestedDeclaration.ToString()); Assert.Equal("(System.String, System.Int32)", model.GetTypeInfo(nestedDeclaration).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(nestedDeclaration).Symbol); } [Fact] public void UnderscoreInCSharp6Foreach() { var source = @" class C { static void Main() { foreach (var _ in M()) { System.Console.Write(_); } } static System.Collections.Generic.IEnumerable<int> M() { System.Console.Write(""M ""); yield return 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "M 1"); } [Fact] public void ShortDiscardDisallowedInForeach() { var source = @" class C { static void Main() { foreach (_ in M()) { } } static System.Collections.Generic.IEnumerable<int> M() { yield return 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,18): error CS8186: A foreach loop must declare its iteration variables. // foreach (_ in M()) Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "_").WithLocation(6, 18) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var discard = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().First(); var symbol = (DiscardSymbol)model.GetSymbolInfo(discard).Symbol.GetSymbol(); Assert.True(symbol.TypeWithAnnotations.Type.IsErrorType()); } [Fact] public void ExistingUnderscoreLocalInLegacyForeach() { var source = @" class C { static void Main() { int _; foreach (var _ in new[] { 1 }) { } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,22): error CS0136: A local or parameter named '_' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var _ in new[] { 1 }) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "_").WithArguments("_").WithLocation(7, 22), // (6,13): warning CS0168: The variable '_' is declared but never used // int _; Diagnostic(ErrorCode.WRN_UnreferencedVar, "_").WithArguments("_").WithLocation(6, 13) ); } [Fact] public void MixedDeconstruction_01() { string source = @" class Program { static void Main(string[] args) { var t = (1, 2); var x = (int x1, int x2) = t; System.Console.WriteLine(x1); System.Console.WriteLine(x2); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (7,18): error CS8185: A declaration is not allowed in this context. // var x = (int x1, int x2) = t; Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(7, 18) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); } [Fact] public void MixedDeconstruction_02() { string source = @" class Program { static void Main(string[] args) { var t = (1, 2); int z; (int x1, z) = t; System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "1") .VerifyIL("Program.Main", @" { // Code size 32 (0x20) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0, //t int V_1, //z int V_2) //x1 IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000a: ldloc.0 IL_000b: dup IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0011: stloc.2 IL_0012: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0017: stloc.1 IL_0018: ldloc.2 IL_0019: call ""void System.Console.WriteLine(int)"" IL_001e: nop IL_001f: ret }"); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); } [Fact] public void MixedDeconstruction_03() { string source = @" class Program { static void Main(string[] args) { var t = (1, 2); int z; for ((int x1, z) = t; ; ) { System.Console.WriteLine(x1); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "1") .VerifyIL("Program.Main", @" { // Code size 39 (0x27) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0, //t int V_1, //z int V_2) //x1 IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000a: ldloc.0 IL_000b: dup IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0011: stloc.2 IL_0012: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0017: stloc.1 IL_0018: br.s IL_0024 IL_001a: nop IL_001b: ldloc.2 IL_001c: call ""void System.Console.WriteLine(int)"" IL_0021: nop IL_0022: br.s IL_0026 IL_0024: br.s IL_001a IL_0026: ret }"); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var symbolInfo = model.GetSymbolInfo(x1Ref); Assert.Equal(symbolInfo.Symbol, model.GetDeclaredSymbol(x1)); Assert.Equal(SpecialType.System_Int32, symbolInfo.Symbol.GetTypeOrReturnType().SpecialType); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(int x1, z)", lhs.ToString()); Assert.Equal("(System.Int32 x1, System.Int32 z)", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 x1, System.Int32 z)", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); } [Fact] public void MixedDeconstruction_03CSharp9() { string source = @" class Program { static void Main(string[] args) { var t = (1, 2); int z; for ((int x1, z) = t; ; ) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (8,14): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // for ((int x1, z) = t; ; ) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int x1, z) = t").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(8, 14)); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); } [Fact] public void MixedDeconstruction_04() { string source = @" class Program { static void Main(string[] args) { var t = (1, 2); for (; ; (int x1, int x2) = t) { System.Console.WriteLine(x1); System.Console.WriteLine(x2); } } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (7,19): error CS8185: A declaration is not allowed in this context. // for (; ; (int x1, int x2) = t) Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(7, 19), // (9,38): error CS0103: The name 'x1' does not exist in the current context // System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(9, 38), // (10,38): error CS0103: The name 'x2' does not exist in the current context // System.Console.WriteLine(x2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(10, 38) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1); var symbolInfo = model.GetSymbolInfo(x1Ref); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2); symbolInfo = model.GetSymbolInfo(x2Ref); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); } [Fact] public void MixedDeconstruction_05() { string source = @" class Program { static void Main(string[] args) { foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) }) { System.Console.WriteLine(x1); System.Console.WriteLine(x2); } } static int _M; static ref int M(out int x) { x = 2; return ref _M; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,34): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) }) Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "args is var x2").WithLocation(6, 34), // (6,34): error CS0029: Cannot implicitly convert type 'int' to 'bool' // foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) }) Diagnostic(ErrorCode.ERR_NoImplicitConv, "args is var x2").WithArguments("int", "bool").WithLocation(6, 34), // (6,18): error CS8186: A foreach loop must declare its iteration variables. // foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) }) Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(M(out var x1), args is var x2, _)").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.Equal("int", model.GetTypeInfo(x1Ref).Type.ToDisplayString()); model = compilation.GetSemanticModel(tree); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); Assert.Equal("string[]", model.GetTypeInfo(x2Ref).Type.ToDisplayString()); VerifyModelForLocal(model, x1, LocalDeclarationKind.OutVariable, x1Ref); VerifyModelForLocal(model, x2, LocalDeclarationKind.PatternVariable, x2Ref); } [Fact] public void ForeachIntoExpression() { string source = @" class Program { static void Main(string[] args) { foreach (M(out var x1) in new[] { 1, 2, 3 }) { System.Console.WriteLine(x1); } } static int _M; static ref int M(out int x) { x = 2; return ref _M; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,32): error CS0230: Type and identifier are both required in a foreach statement // foreach (M(out var x1) in new[] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(6, 32) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.Equal("int", model.GetTypeInfo(x1Ref).Type.ToDisplayString()); VerifyModelForLocal(model, x1, LocalDeclarationKind.OutVariable, x1Ref); } [Fact] public void MixedDeconstruction_06() { string source = @" class Program { static void Main(string[] args) { foreach (M1(M2(out var x1, args is var x2), x1, x2) in new[] {1, 2, 3}) { System.Console.WriteLine(x1); System.Console.WriteLine(x2); } } static int _M; static ref int M1(int m2, int x, string[] y) { return ref _M; } static int M2(out int x, bool b) => x = 2; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,61): error CS0230: Type and identifier are both required in a foreach statement // foreach (M1(M2(out var x1, args is var x2), x1, x2) in new[] {1, 2, 3}) Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(6, 61) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReferences(tree, "x1"); Assert.Equal("int", model.GetTypeInfo(x1Ref.First()).Type.ToDisplayString()); model = compilation.GetSemanticModel(tree); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReferences(tree, "x2"); Assert.Equal("string[]", model.GetTypeInfo(x2Ref.First()).Type.ToDisplayString()); VerifyModelForLocal(model, x1, LocalDeclarationKind.OutVariable, x1Ref.ToArray()); VerifyModelForLocal(model, x2, LocalDeclarationKind.PatternVariable, x2Ref.ToArray()); } [Fact] public void MixedDeconstruction_07() { string source = @" class Program { static void Main(string[] args) { var t = (1, ("""", true)); string y; for ((int x, (y, var z)) = t; ; ) { System.Console.Write(x); System.Console.Write(z); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation, expectedOutput: "1True") .VerifyIL("Program.Main", @" { // Code size 73 (0x49) .maxstack 4 .locals init (System.ValueTuple<int, System.ValueTuple<string, bool>> V_0, //t string V_1, //y int V_2, //x bool V_3, //z System.ValueTuple<string, bool> V_4) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldstr """" IL_0009: ldc.i4.1 IL_000a: newobj ""System.ValueTuple<string, bool>..ctor(string, bool)"" IL_000f: call ""System.ValueTuple<int, System.ValueTuple<string, bool>>..ctor(int, System.ValueTuple<string, bool>)"" IL_0014: ldloc.0 IL_0015: dup IL_0016: ldfld ""System.ValueTuple<string, bool> System.ValueTuple<int, System.ValueTuple<string, bool>>.Item2"" IL_001b: stloc.s V_4 IL_001d: ldfld ""int System.ValueTuple<int, System.ValueTuple<string, bool>>.Item1"" IL_0022: stloc.2 IL_0023: ldloc.s V_4 IL_0025: ldfld ""string System.ValueTuple<string, bool>.Item1"" IL_002a: stloc.1 IL_002b: ldloc.s V_4 IL_002d: ldfld ""bool System.ValueTuple<string, bool>.Item2"" IL_0032: stloc.3 IL_0033: br.s IL_0046 IL_0035: nop IL_0036: ldloc.2 IL_0037: call ""void System.Console.Write(int)"" IL_003c: nop IL_003d: ldloc.3 IL_003e: call ""void System.Console.Write(bool)"" IL_0043: nop IL_0044: br.s IL_0048 IL_0046: br.s IL_0035 IL_0048: ret }"); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xRef = GetReference(tree, "x"); VerifyModelForDeconstructionLocal(model, x, xRef); var xSymbolInfo = model.GetSymbolInfo(xRef); Assert.Equal(xSymbolInfo.Symbol, model.GetDeclaredSymbol(x)); Assert.Equal(SpecialType.System_Int32, xSymbolInfo.Symbol.GetTypeOrReturnType().SpecialType); var z = GetDeconstructionVariable(tree, "z"); var zRef = GetReference(tree, "z"); VerifyModelForDeconstructionLocal(model, z, zRef); var zSymbolInfo = model.GetSymbolInfo(zRef); Assert.Equal(zSymbolInfo.Symbol, model.GetDeclaredSymbol(z)); Assert.Equal(SpecialType.System_Boolean, zSymbolInfo.Symbol.GetTypeOrReturnType().SpecialType); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(2); Assert.Equal(@"(int x, (y, var z))", lhs.ToString()); Assert.Equal("(System.Int32 x, (System.String y, System.Boolean z))", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 x, (System.String y, System.Boolean z))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); } [Fact] public void IncompleteDeclarationIsSeenAsTupleLiteral() { string source = @" class C { static void Main() { (int x1, string x2); System.Console.WriteLine(x1); System.Console.WriteLine(x2); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,10): error CS8185: A declaration is not allowed in this context. // (int x1, string x2); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 10), // (6,18): error CS8185: A declaration is not allowed in this context. // (int x1, string x2); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "string x2").WithLocation(6, 18), // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (int x1, string x2); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x1, string x2)").WithLocation(6, 9), // (6,10): error CS0165: Use of unassigned local variable 'x1' // (int x1, string x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 10), // (6,18): error CS0165: Use of unassigned local variable 'x2' // (int x1, string x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "string x2").WithArguments("x2").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.Equal("int", model.GetTypeInfo(x1Ref).Type.ToDisplayString()); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); Assert.Equal("string", model.GetTypeInfo(x2Ref).Type.ToDisplayString()); VerifyModelForDeconstruction(model, x1, LocalDeclarationKind.DeclarationExpressionVariable, x1Ref); VerifyModelForDeconstruction(model, x2, LocalDeclarationKind.DeclarationExpressionVariable, x2Ref); } [Fact] [WorkItem(15893, "https://github.com/dotnet/roslyn/issues/15893")] public void DeconstructionOfOnlyOneElement() { string source = @" class C { static void Main() { var (p2) = (1, 2); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,16): error CS1003: Syntax error, ',' expected // var (p2) = (1, 2); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(",", ")").WithLocation(6, 16), // (6,16): error CS1001: Identifier expected // var (p2) = (1, 2); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(6, 16) ); } [Fact] [WorkItem(14876, "https://github.com/dotnet/roslyn/issues/14876")] public void TupleTypeInDeconstruction() { string source = @" class C { static void Main() { (int x, (string, long) y) = M(); System.Console.Write($""{x} {y}""); } static (int, (string, long)) M() { return (5, (""Goo"", 34983490)); } } "; var comp = CompileAndVerify(source, expectedOutput: "5 (Goo, 34983490)"); comp.VerifyDiagnostics(); } [Fact] [WorkItem(12468, "https://github.com/dotnet/roslyn/issues/12468")] public void RefReturningVarInvocation() { string source = @" class C { static int i; static void Main() { int x = 0, y = 0; (var(x, y)) = 42; // parsed as invocation System.Console.Write(i); } static ref int var(int a, int b) { return ref i; } } "; var comp = CompileAndVerify(source, expectedOutput: "42", verify: Verification.Passes); comp.VerifyDiagnostics(); } [Fact] void InvokeVarForLvalueInParens() { var source = @" class Program { public static void Main() { (var(x, y)) = 10; System.Console.WriteLine(z); } static int x = 1, y = 2, z = 3; static ref int var(int x, int y) { return ref z; } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); // PEVerify fails with ref return https://github.com/dotnet/roslyn/issues/12285 CompileAndVerify(compilation, expectedOutput: "10", verify: Verification.Fails); } [Fact] [WorkItem(16106, "https://github.com/dotnet/roslyn/issues/16106")] public void DefAssignmentsStruct001() { string source = @" using System.Collections.Generic; public class MyClass { public static void Main() { ((int, int), string)[] arr = new((int, int), string)[1]; Test5(arr); } public static void Test4(IEnumerable<(KeyValuePair<int, int>, string)> en) { foreach ((KeyValuePair<int, int> kv, string s) in en) { var a = kv.Key; // false error CS0170: Use of possibly unassigned field } } public static void Test5(IEnumerable<((int, int), string)> en) { foreach (((int, int k) t, string s) in en) { var a = t.k; // false error CS0170: Use of possibly unassigned field System.Console.WriteLine(a); } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "0"); } [Fact] [WorkItem(16106, "https://github.com/dotnet/roslyn/issues/16106")] public void DefAssignmentsStruct002() { string source = @" public class MyClass { public static void Main() { var data = new int[10]; var arr = new int[2]; foreach (arr[out int size] in data) {} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,36): error CS0230: Type and identifier are both required in a foreach statement // foreach (arr[out int size] in data) {} Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(9, 36) ); } [Fact] [WorkItem(16106, "https://github.com/dotnet/roslyn/issues/16106")] public void DefAssignmentsStruct003() { string source = @" public class MyClass { public static void Main() { var data = new (int, int)[10]; var arr = new int[2]; foreach ((arr[out int size], int b) in data) {} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,27): error CS1615: Argument 1 may not be passed with the 'out' keyword // foreach ((arr[out int size], int b) in data) {} Diagnostic(ErrorCode.ERR_BadArgExtraRef, "int size").WithArguments("1", "out").WithLocation(9, 27), // (9,18): error CS8186: A foreach loop must declare its iteration variables. // foreach ((arr[out int size], int b) in data) {} Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(arr[out int size], int b)").WithLocation(9, 18) ); } [Fact] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_01() { string source = @" class C { static event System.Action E; static void Main() { (E, _) = (null, 1); System.Console.WriteLine(E == null); (E, _) = (Handler, 1); E(); } static void Handler() { System.Console.WriteLine(""Handler""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"True Handler"); comp.VerifyDiagnostics(); } [Fact] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_02() { string source = @" struct S { event System.Action E; class C { static void Main() { var s = new S(); (s.E, _) = (null, 1); System.Console.WriteLine(s.E == null); (s.E, _) = (Handler, 1); s.E(); } static void Handler() { System.Console.WriteLine(""Handler""); } } } "; var comp = CompileAndVerify(source, expectedOutput: @"True Handler"); comp.VerifyDiagnostics(); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.WinRTNeedsWindowsDesktop)] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_03() { string source1 = @" public interface EventInterface { event System.Action E; } "; var comp1 = CreateEmptyCompilation(source1, WinRtRefs, TestOptions.ReleaseWinMD, TestOptions.Regular); string source2 = @" class C : EventInterface { public event System.Action E; static void Main() { var c = new C(); c.Test(); } void Test() { (E, _) = (null, 1); System.Console.WriteLine(E == null); (E, _) = (Handler, 1); E(); } static void Handler() { System.Console.WriteLine(""Handler""); } } "; var comp2 = CompileAndVerify(source2, targetFramework: TargetFramework.Empty, expectedOutput: @"True Handler", references: WinRtRefs.Concat(new[] { ValueTupleRef, comp1.ToMetadataReference() })); comp2.VerifyDiagnostics(); Assert.True(comp2.Compilation.GetMember<IEventSymbol>("C.E").IsWindowsRuntimeEvent); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.WinRTNeedsWindowsDesktop)] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_04() { string source1 = @" public interface EventInterface { event System.Action E; } "; var comp1 = CreateEmptyCompilation(source1, WinRtRefs, TestOptions.ReleaseWinMD, TestOptions.Regular); string source2 = @" struct S : EventInterface { public event System.Action E; class C { S s = new S(); static void Main() { var c = new C(); (GetC(c).s.E, _) = (null, GetInt(1)); System.Console.WriteLine(c.s.E == null); (GetC(c).s.E, _) = (Handler, GetInt(2)); c.s.E(); } static int GetInt(int i) { System.Console.WriteLine(i); return i; } static C GetC(C c) { System.Console.WriteLine(""GetC""); return c; } static void Handler() { System.Console.WriteLine(""Handler""); } } } "; var comp2 = CompileAndVerify(source2, targetFramework: TargetFramework.Empty, expectedOutput: @"GetC 1 True GetC 2 Handler", references: WinRtRefs.Concat(new[] { ValueTupleRef, comp1.ToMetadataReference() })); comp2.VerifyDiagnostics(); Assert.True(comp2.Compilation.GetMember<IEventSymbol>("S.E").IsWindowsRuntimeEvent); } [Fact] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_05() { string source = @" class C { public static event System.Action E; } class Program { static void Main() { (C.E, _) = (null, 1); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,12): error CS0070: The event 'C.E' can only appear on the left hand side of += or -= (except when used from within the type 'C') // (C.E, _) = (null, 1); Diagnostic(ErrorCode.ERR_BadEventUsage, "E").WithArguments("C.E", "C").WithLocation(11, 12) ); } [Fact] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_06() { string source = @" class C { static event System.Action E { add {} remove {} } static void Main() { (E, _) = (null, 1); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (12,10): error CS0079: The event 'C.E' can only appear on the left hand side of += or -= // (E, _) = (null, 1); Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "E").WithArguments("C.E").WithLocation(12, 10) ); } [Fact] public void SimpleAssignInConstructor() { string source = @" public class C { public long x; public string y; public C(int a, string b) => (x, y) = (a, b); public static void Main() { var c = new C(1, ""hello""); System.Console.WriteLine(c.x + "" "" + c.y); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C..ctor(int, string)", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (long V_0, string V_1) IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.1 IL_0007: conv.i8 IL_0008: stloc.0 IL_0009: ldarg.2 IL_000a: stloc.1 IL_000b: ldarg.0 IL_000c: ldloc.0 IL_000d: stfld ""long C.x"" IL_0012: ldarg.0 IL_0013: ldloc.1 IL_0014: stfld ""string C.y"" IL_0019: ret }"); } [Fact] public void DeconstructAssignInConstructor() { string source = @" public class C { public long x; public string y; public C(C oldC) => (x, y) = oldC; public C() { } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } public static void Main() { var oldC = new C() { x = 1, y = ""hello"" }; var newC = new C(oldC); System.Console.WriteLine(newC.x + "" "" + newC.y); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C..ctor(C)", @" { // Code size 34 (0x22) .maxstack 3 .locals init (int V_0, string V_1, long V_2) IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.1 IL_0007: ldloca.s V_0 IL_0009: ldloca.s V_1 IL_000b: callvirt ""void C.Deconstruct(out int, out string)"" IL_0010: ldloc.0 IL_0011: conv.i8 IL_0012: stloc.2 IL_0013: ldarg.0 IL_0014: ldloc.2 IL_0015: stfld ""long C.x"" IL_001a: ldarg.0 IL_001b: ldloc.1 IL_001c: stfld ""string C.y"" IL_0021: ret }"); } [Fact] public void AssignInConstructorWithProperties() { string source = @" public class C { public long X { get; set; } public string Y { get; } private int z; public ref int Z { get { return ref z; } } public C(int a, string b, ref int c) => (X, Y, Z) = (a, b, c); public static void Main() { int number = 2; var c = new C(1, ""hello"", ref number); System.Console.WriteLine($""{c.X} {c.Y} {c.Z}""); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello 2"); comp.VerifyDiagnostics(); comp.VerifyIL("C..ctor(int, string, ref int)", @" { // Code size 39 (0x27) .maxstack 4 .locals init (long V_0, string V_1, int V_2, long V_3) IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: call ""ref int C.Z.get"" IL_000c: ldarg.1 IL_000d: conv.i8 IL_000e: stloc.0 IL_000f: ldarg.2 IL_0010: stloc.1 IL_0011: ldarg.3 IL_0012: ldind.i4 IL_0013: stloc.2 IL_0014: ldarg.0 IL_0015: ldloc.0 IL_0016: dup IL_0017: stloc.3 IL_0018: call ""void C.X.set"" IL_001d: ldarg.0 IL_001e: ldloc.1 IL_001f: stfld ""string C.<Y>k__BackingField"" IL_0024: ldloc.2 IL_0025: stind.i4 IL_0026: ret }"); } [Fact] public void VerifyDeconstructionInAsync() { var source = @" using System.Threading.Tasks; class C { static void Main() { System.Console.Write(C.M().Result); } static async Task<int> M() { await Task.Delay(0); var (x, y) = (1, 2); return x + y; } } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void DeconstructionWarnsForSelfAssignment() { var source = @" class C { object x = 1; static object y = 2; void M() { ((x, x), this.x, C.y) = ((x, (1, 2)), x, y); } } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,11): warning CS1717: Assignment made to same variable; did you mean to assign something else? // ((x, x), this.x, C.y) = ((x, (1, 2)), x, y); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(8, 11), // (8,18): warning CS1717: Assignment made to same variable; did you mean to assign something else? // ((x, x), this.x, C.y) = ((x, (1, 2)), x, y); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "this.x").WithLocation(8, 18), // (8,26): warning CS1717: Assignment made to same variable; did you mean to assign something else? // ((x, x), this.x, C.y) = ((x, (1, 2)), x, y); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "C.y").WithLocation(8, 26) ); } [Fact] public void DeconstructionWarnsForSelfAssignment2() { var source = @" class C { object x = 1; static object y = 2; void M() { object z = 3; (x, (y, z)) = (x, (y, z)); } } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (9,10): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (x, (y, z)) = (x, (y, z)); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x"), // (9,14): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (x, (y, z)) = (x, (y, z)); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "y").WithLocation(9, 14), // (9,17): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (x, (y, z)) = (x, (y, z)); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "z").WithLocation(9, 17) ); } [Fact] public void DeconstructionWarnsForSelfAssignment_WithUserDefinedConversionOnElement() { var source = @" class C { object x = 1; static C y = null; void M() { (x, y) = (x, (C)(D)y); } public static implicit operator C(D d) => null; } class D { public static implicit operator D(C c) => null; } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,10): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (x, y) = (x, (C)(D)y); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(8, 10) ); } [Fact] public void DeconstructionWarnsForSelfAssignment_WithNestedConversions() { var source = @" class C { object x = 1; int y = 2; byte b = 3; void M() { // The conversions on the right-hand-side: // - a deconstruction conversion // - an implicit tuple literal conversion on the entire right-hand-side // - another implicit tuple literal conversion on the nested tuple // - a conversion on element `b` (_, (x, y)) = (1, (x, b)); } } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (14,14): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (_, (x, y)) = (1, (x, b)); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(14, 14) ); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DeconstructionWarnsForSelfAssignment_WithExplicitTupleConversion() { var source = @" class C { int y = 2; byte b = 3; void M() { // The conversions on the right-hand-side: // - a deconstruction conversion on the entire right-hand-side // - an identity conversion as its operand // - an explicit tuple literal conversion as its operand (y, _) = ((int, int))(y, b); } } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( ); var tree = comp.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); Assert.Equal("((int, int))(y, b)", node.ToString()); comp.VerifyOperationTree(node, expectedOperationTree: @" IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32)) (Syntax: '((int, int))(y, b)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Int32 y, System.Int32 b)) (Syntax: '(y, b)') NaturalType: (System.Int32 y, System.Byte b) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.Int32 C.y (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'y') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.Byte C.b (OperationKind.FieldReference, Type: System.Byte) (Syntax: 'b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'b') "); } [Fact] public void DeconstructionWarnsForSelfAssignment_WithDeconstruct() { var source = @" class C { object x = 1; static object y = 2; void M() { object z = 3; (x, (y, z)) = (x, y); } } static class Extensions { public static void Deconstruct(this object input, out object output1, out object output2) { output1 = input; output2 = input; } }"; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (9,10): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (x, (y, z)) = (x, y); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(9, 10) ); } [Fact] public void TestDeconstructOnErrorType() { var source = @" class C { Error M() { int x, y; (x, y) = M(); throw null; } }"; var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll); // no ValueTuple reference comp.VerifyDiagnostics( // (4,5): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // Error M() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 5) ); } [Fact] public void TestDeconstructOnErrorTypeFromImageReference() { var missing_cs = "public class Missing { }"; var missing = CreateCompilationWithMscorlib45(missing_cs, options: TestOptions.DebugDll, assemblyName: "missing"); var lib_cs = "public class C { public Missing M() { throw null; } }"; var lib = CreateCompilationWithMscorlib45(lib_cs, references: new[] { missing.EmitToImageReference() }, options: TestOptions.DebugDll); var source = @" class D { void M() { int x, y; (x, y) = new C().M(); throw null; } }"; var comp = CreateCompilationWithMscorlib45(source, references: new[] { lib.EmitToImageReference() }, options: TestOptions.DebugDll); // no ValueTuple reference comp.VerifyDiagnostics( // (7,18): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (x, y) = new C().M(); Diagnostic(ErrorCode.ERR_NoTypeDef, "new C().M").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18) ); } [Fact] public void TestDeconstructOnErrorTypeFromCompilationReference() { var missing_cs = "public class Missing { }"; var missing = CreateCompilationWithMscorlib45(missing_cs, options: TestOptions.DebugDll, assemblyName: "missing"); var lib_cs = "public class C { public Missing M() { throw null; } }"; var lib = CreateCompilationWithMscorlib45(lib_cs, references: new[] { missing.ToMetadataReference() }, options: TestOptions.DebugDll); var source = @" class D { void M() { int x, y; (x, y) = new C().M(); throw null; } }"; var comp = CreateCompilationWithMscorlib45(source, references: new[] { lib.ToMetadataReference() }, options: TestOptions.DebugDll); // no ValueTuple reference comp.VerifyDiagnostics( // (7,18): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (x, y) = new C().M(); Diagnostic(ErrorCode.ERR_NoTypeDef, "new C().M").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18) ); } [Fact, WorkItem(17756, "https://github.com/dotnet/roslyn/issues/17756")] public void TestDiscardedAssignmentNotLvalue() { var source = @" class Program { struct S1 { public int field; public int Increment() => field++; } static void Main() { S1 v = default(S1); v.Increment(); (_ = v).Increment(); System.Console.WriteLine(v.field); } } "; string expectedOutput = @"1"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void TupleCastInDeconstruction() { var source = @" class C { static void Main() { var t = (1, 2); var (a, b) = ((byte, byte))t; System.Console.Write($""{a} {b}""); } }"; CompileAndVerify(source, expectedOutput: @"1 2"); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void TupleCastInDeconstruction2() { var source = @" class C { static void Main() { var t = (new C(), new D()); var (a, _) = ((byte, byte))t; System.Console.Write($""{a}""); } public static explicit operator byte(C c) { System.Console.Write(""Convert ""); return 1; } } class D { public static explicit operator byte(D c) { System.Console.Write(""Convert2 ""); return 2; } }"; CompileAndVerify(source, expectedOutput: @"Convert Convert2 1"); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void TupleCastInDeconstruction3() { var source = @" class C { static int A { set { System.Console.Write(""A ""); } } static int B { set { System.Console.Write(""B""); } } static void Main() { (A, B) = ((byte, byte))(new C(), new D()); } public static explicit operator byte(C c) { System.Console.Write(""Convert ""); return 1; } public C() { System.Console.Write(""C ""); } } class D { public static explicit operator byte(D c) { System.Console.Write(""Convert2 ""); return 2; } public D() { System.Console.Write(""D ""); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"C Convert D Convert2 A B").Compilation; var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); Assert.Equal("((byte, byte))(new C(), new D())", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Byte, System.Byte)) (Syntax: '((byte, byt ... ), new D())') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Byte, System.Byte)) (Syntax: '(new C(), new D())') NaturalType: (C, D) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Byte C.op_Explicit(C c)) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 'new C()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Byte C.op_Explicit(C c)) Operand: IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Byte D.op_Explicit(D c)) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 'new D()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Byte D.op_Explicit(D c)) Operand: IObjectCreationOperation (Constructor: D..ctor()) (OperationKind.ObjectCreation, Type: D) (Syntax: 'new D()') Arguments(0) Initializer: null "); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void TupleCastInDeconstruction4() { var source = @" class C { static void Main() { var (a, _) = ((short, short))((int, int))(1L, 2L); System.Console.Write($""{a}""); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1").Compilation; var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().ElementAt(1); Assert.Equal("((int, int))(1L, 2L)", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32)) (Syntax: '((int, int))(1L, 2L)') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1L, 2L)') NaturalType: (System.Int64, System.Int64) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1L') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 1) (Syntax: '1L') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2L') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 2) (Syntax: '2L') "); Assert.Equal("((short, short))((int, int))(1L, 2L)", node.Parent.ToString()); compilation.VerifyOperationTree(node.Parent, expectedOperationTree: @" IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int16, System.Int16)) (Syntax: '((short, sh ... t))(1L, 2L)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32)) (Syntax: '((int, int))(1L, 2L)') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1L, 2L)') NaturalType: (System.Int64, System.Int64) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1L') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 1) (Syntax: '1L') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2L') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 2) (Syntax: '2L') "); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void UserDefinedCastInDeconstruction() { var source = @" class C { static void Main() { var c = new C(); var (a, b) = ((byte, byte))c; System.Console.Write($""{a} {b}""); } public static explicit operator (byte, byte)(C c) { return (3, 4); } }"; CompileAndVerify(source, expectedOutput: @"3 4"); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void DeconstructionLoweredToNothing() { var source = @" class C { static void M() { for (var(_, _) = (1, 2); ; (_, _) = (3, 4)) { } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp); verifier.VerifyIL("C.M", @" { // Code size 2 (0x2) .maxstack 0 IL_0000: br.s IL_0000 }"); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void DeconstructionLoweredToNothing2() { var source = @" class C { static void M() { (_, _) = (1, 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp); verifier.VerifyIL("C.M", @" { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void DeconstructionLoweredToNothing3() { var source = @" class C { static void Main() { foreach (var(_, _) in new[] { (1, 2) }) { System.Console.Write(""once""); } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "once"); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact] public void InferredName() { var source = @"class C { static void Main() { int x = 0, y = 1; var t = (x, y); var (a, b) = t; } }"; // C# 7.0 var comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(); // C# 7.1 comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact] public void InferredName_ConditionalOperator() { var source = @"class C { static void M(int a, int b, bool c) { (var x, var y) = c ? (a, default(object)) : (b, null); (x, y) = c ? (a, default(string)) : (b, default(object)); } }"; // C# 7.0 var comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(); // C# 7.1 comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact] public void InferredName_ImplicitArray() { var source = @"class C { static void M(int x) { int y; object z; (y, z) = (new [] { (x, default(object)), (2, 3) })[0]; } }"; // C# 7.0 var comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(); // C# 7.1 comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/32006")] public void InferredName_Lambda() { // See https://github.com/dotnet/roslyn/issues/32006 // need to relax assertion in GetImplicitTupleLiteralConversion var source = @"class C { static T F<T>(System.Func<object, bool, T> f) { return f(null, false); } static void M() { var (x, y) = F((a, b) => { if (b) return (default(object), a); return (null, null); }); } }"; // C# 7.0 var comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(); // C# 7.1 comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact] public void InferredName_ConditionalOperator_LongTuple() { var source = @"class C { static void M(object a, object b, bool c) { var (_1, _2, _3, _4, _5, _6, _7, _8, _9, _10) = c ? (1, 2, 3, 4, 5, 6, 7, a, b, 10) : (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); } }"; // C# 7.0 var comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(); // C# 7.1 comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact] public void InferredName_ConditionalOperator_UseSite() { var source = @"class C { static void M(int a, int b, bool c) { var (x, y) = c ? ((object)1, a) : (b, 2); } } namespace System { struct ValueTuple<T1, T2> { public T1 Item1; private T2 Item2; public ValueTuple(T1 item1, T2 item2) => throw null; } }"; var expected = new[] { // (12,19): warning CS0649: Field '(T1, T2).Item1' is never assigned to, and will always have its default value // public T1 Item1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Item1").WithArguments("(T1, T2).Item1", "").WithLocation(12, 19), // (13,20): warning CS0169: The field '(T1, T2).Item2' is never used // private T2 Item2; Diagnostic(ErrorCode.WRN_UnreferencedField, "Item2").WithArguments("(T1, T2).Item2").WithLocation(13, 20) }; // C# 7.0 var comp = CreateCompilation( source, assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08", parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(expected); // C# 7.1 comp = CreateCompilation( source, assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08", parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(expected); } [Fact] public void InferredName_ConditionalOperator_UseSite_AccessingWithinConstructor() { var source = @"class C { static void M(int a, int b, bool c) { var (x, y) = c ? ((object)1, a) : (b, 2); } } namespace System { struct ValueTuple<T1, T2> { public T1 Item1; private T2 Item2; public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } } }"; var expected = new[] { // (13,20): warning CS0169: The field '(T1, T2).Item2' is never used // private T2 Item2; Diagnostic(ErrorCode.WRN_UnreferencedField, "Item2").WithArguments("(T1, T2).Item2").WithLocation(13, 20), // (14,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(14, 16), // (14,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(14, 16), // (17,13): error CS0229: Ambiguity between '(T1, T2).Item2' and '(T1, T2).Item2' // Item2 = item2; Diagnostic(ErrorCode.ERR_AmbigMember, "Item2").WithArguments("(T1, T2).Item2", "(T1, T2).Item2").WithLocation(17, 13) }; // C# 7.0 var comp = CreateCompilation( source, assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08", parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(expected); // C# 7.1 comp = CreateCompilation( source, assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08", parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(expected); } [Fact] public void TestGetDeconstructionInfoOnIncompleteCode() { string source = @" class C { void M() { var (y1, y2) =} void Deconstruct(out int x1, out int x2) { x1 = 1; x2 = 2; } } "; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First(); Assert.Equal("var (y1, y2) =", node.ToString()); var info = model.GetDeconstructionInfo(node); Assert.Null(info.Method); Assert.Empty(info.Nested); } [Fact] public void TestDeconstructStructThis() { string source = @" public struct S { int I; public static void Main() { S s = new S(); s.M(); } public void M() { this.I = 42; var (x, (y, z)) = (this, this /* mutating deconstruction */); System.Console.Write($""{x.I} {y} {z}""); } void Deconstruct(out int x1, out int x2) { x1 = I++; x2 = I++; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "42 42 43"); } [Fact] public void TestDeconstructClassThis() { string source = @" public class C { int I; public static void Main() { C c = new C(); c.M(); } public void M() { this.I = 42; var (x, (y, z)) = (this, this /* mutating deconstruction */); System.Console.Write($""{x.I} {y} {z}""); } void Deconstruct(out int x1, out int x2) { x1 = I++; x2 = I++; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "44 42 43"); } [Fact] public void AssigningConditional_OutParams() { string source = @" using System; class C { static void Main() { Test(true, false); Test(false, true); Test(false, false); } static void Test(bool b1, bool b2) { M(out int x, out int y, b1, b2); Console.Write(x); Console.Write(y); } static void M(out int x, out int y, bool b1, bool b2) { (x, y) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60); } } "; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "102030405060"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @" { // Code size 33 (0x21) .maxstack 2 IL_0000: ldarg.2 IL_0001: brtrue.s IL_0018 IL_0003: ldarg.3 IL_0004: brtrue.s IL_000f IL_0006: ldarg.0 IL_0007: ldc.i4.s 50 IL_0009: stind.i4 IL_000a: ldarg.1 IL_000b: ldc.i4.s 60 IL_000d: stind.i4 IL_000e: ret IL_000f: ldarg.0 IL_0010: ldc.i4.s 30 IL_0012: stind.i4 IL_0013: ldarg.1 IL_0014: ldc.i4.s 40 IL_0016: stind.i4 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.s 10 IL_001b: stind.i4 IL_001c: ldarg.1 IL_001d: ldc.i4.s 20 IL_001f: stind.i4 IL_0020: ret }"); } [Fact] public void AssigningConditional_VarDeconstruction() { string source = @" using System; class C { static void Main() { M(true, false); M(false, true); M(false, false); } static void M(bool b1, bool b2) { var (x, y) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60); Console.Write(x); Console.Write(y); } } "; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "102030405060"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @" { // Code size 41 (0x29) .maxstack 1 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: brtrue.s IL_0016 IL_0003: ldarg.1 IL_0004: brtrue.s IL_000e IL_0006: ldc.i4.s 50 IL_0008: stloc.0 IL_0009: ldc.i4.s 60 IL_000b: stloc.1 IL_000c: br.s IL_001c IL_000e: ldc.i4.s 30 IL_0010: stloc.0 IL_0011: ldc.i4.s 40 IL_0013: stloc.1 IL_0014: br.s IL_001c IL_0016: ldc.i4.s 10 IL_0018: stloc.0 IL_0019: ldc.i4.s 20 IL_001b: stloc.1 IL_001c: ldloc.0 IL_001d: call ""void System.Console.Write(int)"" IL_0022: ldloc.1 IL_0023: call ""void System.Console.Write(int)"" IL_0028: ret }"); } [Fact] public void AssigningConditional_MixedDeconstruction() { string source = @" using System; class C { static void Main() { M(true, false); M(false, true); M(false, false); } static void M(bool b1, bool b2) { (var x, long y) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60); Console.Write(x); Console.Write(y); } } "; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "102030405060"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @" { // Code size 50 (0x32) .maxstack 1 .locals init (int V_0, //x long V_1, //y long V_2) IL_0000: ldarg.0 IL_0001: brtrue.s IL_001c IL_0003: ldarg.1 IL_0004: brtrue.s IL_0011 IL_0006: ldc.i4.s 60 IL_0008: conv.i8 IL_0009: stloc.2 IL_000a: ldc.i4.s 50 IL_000c: stloc.0 IL_000d: ldloc.2 IL_000e: stloc.1 IL_000f: br.s IL_0025 IL_0011: ldc.i4.s 40 IL_0013: conv.i8 IL_0014: stloc.2 IL_0015: ldc.i4.s 30 IL_0017: stloc.0 IL_0018: ldloc.2 IL_0019: stloc.1 IL_001a: br.s IL_0025 IL_001c: ldc.i4.s 20 IL_001e: conv.i8 IL_001f: stloc.2 IL_0020: ldc.i4.s 10 IL_0022: stloc.0 IL_0023: ldloc.2 IL_0024: stloc.1 IL_0025: ldloc.0 IL_0026: call ""void System.Console.Write(int)"" IL_002b: ldloc.1 IL_002c: call ""void System.Console.Write(long)"" IL_0031: ret }"); } [Fact] public void AssigningConditional_SideEffects() { string source = @" using System; class C { static void Main() { M(true, false); M(false, true); M(false, false); SideEffect(true); SideEffect(false); } static int left; static int right; static ref int SideEffect(bool isLeft) { Console.WriteLine($""{(isLeft ? ""left"" : ""right"")}: {(isLeft ? left : right)}""); return ref isLeft ? ref left : ref right; } static void M(bool b1, bool b2) { (SideEffect(isLeft: true), SideEffect(isLeft: false)) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60); } } "; var expected = @"left: 0 right: 0 left: 10 right: 20 left: 30 right: 40 left: 50 right: 60"; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expected); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (int& V_0, int& V_1) IL_0000: ldc.i4.1 IL_0001: call ""ref int C.SideEffect(bool)"" IL_0006: stloc.0 IL_0007: ldc.i4.0 IL_0008: call ""ref int C.SideEffect(bool)"" IL_000d: stloc.1 IL_000e: ldarg.0 IL_000f: brtrue.s IL_0026 IL_0011: ldarg.1 IL_0012: brtrue.s IL_001d IL_0014: ldloc.0 IL_0015: ldc.i4.s 50 IL_0017: stind.i4 IL_0018: ldloc.1 IL_0019: ldc.i4.s 60 IL_001b: stind.i4 IL_001c: ret IL_001d: ldloc.0 IL_001e: ldc.i4.s 30 IL_0020: stind.i4 IL_0021: ldloc.1 IL_0022: ldc.i4.s 40 IL_0024: stind.i4 IL_0025: ret IL_0026: ldloc.0 IL_0027: ldc.i4.s 10 IL_0029: stind.i4 IL_002a: ldloc.1 IL_002b: ldc.i4.s 20 IL_002d: stind.i4 IL_002e: ret }"); } [Fact] public void AssigningConditional_SideEffects_RHS() { string source = @" using System; class C { static void Main() { M(true, false); M(false, true); M(false, false); } static T Echo<T>(T v, int i) { Console.WriteLine(i + "": "" + v); return v; } static void M(bool b1, bool b2) { var (x, y) = Echo(b1, 1) ? Echo((10, 20), 2) : Echo(b2, 3) ? Echo((30, 40), 4) : Echo((50, 60), 5); Console.WriteLine(""x: "" + x); Console.WriteLine(""y: "" + y); Console.WriteLine(); } } "; var expectedOutput = @"1: True 2: (10, 20) x: 10 y: 20 1: False 3: True 4: (30, 40) x: 30 y: 40 1: False 3: False 5: (50, 60) x: 50 y: 60 "; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); comp.VerifyDiagnostics(); } [Fact] public void AssigningConditional_UnusedDeconstruction() { string source = @" class C { static void M(bool b1, bool b2) { (_, _) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60); } } "; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldarg.1 IL_0004: pop IL_0005: ret }"); } [Fact, WorkItem(46562, "https://github.com/dotnet/roslyn/issues/46562")] public void CompoundAssignment() { string source = @" class C { void M() { decimal x = 0; (var y, _) += 0.00m; (int z, _) += z; (var t, _) += (1, 2); } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,17): warning CS0219: The variable 'x' is assigned but its value is never used // decimal x = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 17), // (7,10): error CS8185: A declaration is not allowed in this context. // (var y, _) += 0.00m; Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var y").WithLocation(7, 10), // (7,17): error CS0103: The name '_' does not exist in the current context // (var y, _) += 0.00m; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(7, 17), // (8,10): error CS8185: A declaration is not allowed in this context. // (int z, _) += z; Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int z").WithLocation(8, 10), // (8,10): error CS0165: Use of unassigned local variable 'z' // (int z, _) += z; Diagnostic(ErrorCode.ERR_UseDefViolation, "int z").WithArguments("z").WithLocation(8, 10), // (8,17): error CS0103: The name '_' does not exist in the current context // (int z, _) += z; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(8, 17), // (9,10): error CS8185: A declaration is not allowed in this context. // (var t, _) += (1, 2); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var t").WithLocation(9, 10), // (9,17): error CS0103: The name '_' does not exist in the current context // (var t, _) += (1, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(9, 17) ); } [Fact, WorkItem(50654, "https://github.com/dotnet/roslyn/issues/50654")] public void Repro50654() { string source = @" class C { static void Main() { (int, (int, (int, int), (int, int)))[] vals = new[] { (1, (2, (3, 4), (5, 6))), (11, (12, (13, 14), (15, 16))) }; foreach (var (a, (b, (c, d), (e, f))) in vals) { System.Console.Write($""{a + b + c + d + e + f} ""); } foreach ((int a, (int b, (int c, int d), (int e, int f))) in vals) { System.Console.Write($""{a + b + c + d + e + f} ""); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "21 81 21 81"); } [Fact] public void MixDeclarationAndAssignmentPermutationsOf2() { string source = @" class C { static void Main() { int x1 = 0; (x1, string y1) = new C(); System.Console.WriteLine(x1 + "" "" + y1); int x2; (x2, var y2) = new C(); System.Console.WriteLine(x2 + "" "" + y2); string y3 = """"; (int x3, y3) = new C(); System.Console.WriteLine(x3 + "" "" + y3); string y4; (var x4, y4) = new C(); System.Console.WriteLine(x4 + "" "" + y4); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello 1 hello 1 hello 1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 188 (0xbc) .maxstack 3 .locals init (int V_0, //x1 string V_1, //y1 int V_2, //x2 string V_3, //y2 string V_4, //y3 int V_5, //x3 string V_6, //y4 int V_7, //x4 int V_8, string V_9) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: newobj ""C..ctor()"" IL_0007: ldloca.s V_8 IL_0009: ldloca.s V_9 IL_000b: callvirt ""void C.Deconstruct(out int, out string)"" IL_0010: ldloc.s V_8 IL_0012: stloc.0 IL_0013: ldloc.s V_9 IL_0015: stloc.1 IL_0016: ldloca.s V_0 IL_0018: call ""string int.ToString()"" IL_001d: ldstr "" "" IL_0022: ldloc.1 IL_0023: call ""string string.Concat(string, string, string)"" IL_0028: call ""void System.Console.WriteLine(string)"" IL_002d: newobj ""C..ctor()"" IL_0032: ldloca.s V_8 IL_0034: ldloca.s V_9 IL_0036: callvirt ""void C.Deconstruct(out int, out string)"" IL_003b: ldloc.s V_8 IL_003d: stloc.2 IL_003e: ldloc.s V_9 IL_0040: stloc.3 IL_0041: ldloca.s V_2 IL_0043: call ""string int.ToString()"" IL_0048: ldstr "" "" IL_004d: ldloc.3 IL_004e: call ""string string.Concat(string, string, string)"" IL_0053: call ""void System.Console.WriteLine(string)"" IL_0058: ldstr """" IL_005d: stloc.s V_4 IL_005f: newobj ""C..ctor()"" IL_0064: ldloca.s V_8 IL_0066: ldloca.s V_9 IL_0068: callvirt ""void C.Deconstruct(out int, out string)"" IL_006d: ldloc.s V_8 IL_006f: stloc.s V_5 IL_0071: ldloc.s V_9 IL_0073: stloc.s V_4 IL_0075: ldloca.s V_5 IL_0077: call ""string int.ToString()"" IL_007c: ldstr "" "" IL_0081: ldloc.s V_4 IL_0083: call ""string string.Concat(string, string, string)"" IL_0088: call ""void System.Console.WriteLine(string)"" IL_008d: newobj ""C..ctor()"" IL_0092: ldloca.s V_8 IL_0094: ldloca.s V_9 IL_0096: callvirt ""void C.Deconstruct(out int, out string)"" IL_009b: ldloc.s V_8 IL_009d: stloc.s V_7 IL_009f: ldloc.s V_9 IL_00a1: stloc.s V_6 IL_00a3: ldloca.s V_7 IL_00a5: call ""string int.ToString()"" IL_00aa: ldstr "" "" IL_00af: ldloc.s V_6 IL_00b1: call ""string string.Concat(string, string, string)"" IL_00b6: call ""void System.Console.WriteLine(string)"" IL_00bb: ret }"); } [Fact] public void MixDeclarationAndAssignmentPermutationsOf3() { string source = @" class C { static void Main() { int x1; string y1; (x1, y1, var z1) = new C(); System.Console.WriteLine(x1 + "" "" + y1 + "" "" + z1); int x2; bool z2; (x2, var y2, z2) = new C(); System.Console.WriteLine(x2 + "" "" + y2 + "" "" + z2); string y3; bool z3; (var x3, y3, z3) = new C(); System.Console.WriteLine(x3 + "" "" + y3 + "" "" + z3); bool z4; (var x4, var y4, z4) = new C(); System.Console.WriteLine(x4 + "" "" + y4 + "" "" + z4); string y5; (var x5, y5, var z5) = new C(); System.Console.WriteLine(x5 + "" "" + y5 + "" "" + z5); int x6; (x6, var y6, var z6) = new C(); System.Console.WriteLine(x6 + "" "" + y6 + "" "" + z6); } public void Deconstruct(out int a, out string b, out bool c) { a = 1; b = ""hello""; c = true; } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello True 1 hello True 1 hello True 1 hello True 1 hello True 1 hello True"); comp.VerifyDiagnostics(); } [Fact] public void DontAllowMixedDeclarationAndAssignmentInExpressionContext() { string source = @" class C { static void Main() { int x1 = 0; var z1 = (x1, string y1) = new C(); string y2 = """"; var z2 = (int x2, y2) = new C(); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; CreateCompilation(source).VerifyDiagnostics( // (7,23): error CS8185: A declaration is not allowed in this context. // var z1 = (x1, string y1) = new C(); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "string y1").WithLocation(7, 23), // (9,19): error CS8185: A declaration is not allowed in this context. // var z2 = (int x2, y2) = new C(); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x2").WithLocation(9, 19)); } [Fact] public void DontAllowMixedDeclarationAndAssignmentInForeachDeclarationVariable() { string source = @" class C { static void Main() { int x1; foreach((x1, string y1) in new C[0]); string y2; foreach((int x2, y2) in new C[0]); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; CreateCompilation(source).VerifyDiagnostics( // (6,13): warning CS0168: The variable 'x1' is declared but never used // int x1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(6, 13), // (7,17): error CS8186: A foreach loop must declare its iteration variables. // foreach((x1, string y1) in new C[0]); Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(x1, string y1)").WithLocation(7, 17), // (8,16): warning CS0168: The variable 'y2' is declared but never used // string y2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "y2").WithArguments("y2").WithLocation(8, 16), // (9,17): error CS8186: A foreach loop must declare its iteration variables. // foreach((int x2, y2) in new C[0]); Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(int x2, y2)").WithLocation(9, 17)); } [Fact] public void DuplicateDeclarationOfVariableDeclaredInMixedDeclarationAndAssignment() { string source = @" class C { static void Main() { int x1; string y1; (x1, string y1) = new C(); string y2; (int x2, y2) = new C(); int x2; } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; CreateCompilation(source, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (7,16): warning CS0168: The variable 'y1' is declared but never used // string y1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "y1").WithArguments("y1").WithLocation(7, 16), // (8,21): error CS0128: A local variable or function named 'y1' is already defined in this scope // (x1, string y1) = new C(); Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(8, 21), // (11,13): error CS0128: A local variable or function named 'x2' is already defined in this scope // int x2; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(11, 13), // (11,13): warning CS0168: The variable 'x2' is declared but never used // int x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(11, 13)); } [Fact] public void AssignmentToUndeclaredVariableInMixedDeclarationAndAssignment() { string source = @" class C { static void Main() { (x1, string y1) = new C(); (int x2, y2) = new C(); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; CreateCompilation(source, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (6,10): error CS0103: The name 'x1' does not exist in the current context // (x1, string y1) = new C(); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 10), // (7,18): error CS0103: The name 'y2' does not exist in the current context // (int x2, y2) = new C(); Diagnostic(ErrorCode.ERR_NameNotInContext, "y2").WithArguments("y2").WithLocation(7, 18)); } [Fact] public void MixedDeclarationAndAssignmentInForInitialization() { string source = @" class C { static void Main() { int x1; for((x1, string y1) = new C(); x1 < 2; x1++) System.Console.WriteLine(x1 + "" "" + y1); string y2; for((int x2, y2) = new C(); x2 < 2; x2++) System.Console.WriteLine(x2 + "" "" + y2); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello 1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 109 (0x6d) .maxstack 3 .locals init (int V_0, //x1 string V_1, //y2 string V_2, //y1 int V_3, string V_4, int V_5) //x2 IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_3 IL_0007: ldloca.s V_4 IL_0009: callvirt ""void C.Deconstruct(out int, out string)"" IL_000e: ldloc.3 IL_000f: stloc.0 IL_0010: ldloc.s V_4 IL_0012: stloc.2 IL_0013: br.s IL_0030 IL_0015: ldloca.s V_0 IL_0017: call ""string int.ToString()"" IL_001c: ldstr "" "" IL_0021: ldloc.2 IL_0022: call ""string string.Concat(string, string, string)"" IL_0027: call ""void System.Console.WriteLine(string)"" IL_002c: ldloc.0 IL_002d: ldc.i4.1 IL_002e: add IL_002f: stloc.0 IL_0030: ldloc.0 IL_0031: ldc.i4.2 IL_0032: blt.s IL_0015 IL_0034: newobj ""C..ctor()"" IL_0039: ldloca.s V_3 IL_003b: ldloca.s V_4 IL_003d: callvirt ""void C.Deconstruct(out int, out string)"" IL_0042: ldloc.3 IL_0043: stloc.s V_5 IL_0045: ldloc.s V_4 IL_0047: stloc.1 IL_0048: br.s IL_0067 IL_004a: ldloca.s V_5 IL_004c: call ""string int.ToString()"" IL_0051: ldstr "" "" IL_0056: ldloc.1 IL_0057: call ""string string.Concat(string, string, string)"" IL_005c: call ""void System.Console.WriteLine(string)"" IL_0061: ldloc.s V_5 IL_0063: ldc.i4.1 IL_0064: add IL_0065: stloc.s V_5 IL_0067: ldloc.s V_5 IL_0069: ldc.i4.2 IL_006a: blt.s IL_004a IL_006c: ret }"); } [Fact] public void MixDeclarationAndAssignmentInTupleDeconstructPermutationsOf2() { string source = @" class C { static void Main() { int x1 = 0; (x1, string y1) = (1, ""hello""); System.Console.WriteLine(x1 + "" "" + y1); int x2; (x2, var y2) = (1, ""hello""); System.Console.WriteLine(x2 + "" "" + y2); string y3 = """"; (int x3, y3) = (1, ""hello""); System.Console.WriteLine(x3 + "" "" + y3); string y4; (var x4, y4) = (1, ""hello""); System.Console.WriteLine(x4 + "" "" + y4); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello 1 hello 1 hello 1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 140 (0x8c) .maxstack 3 .locals init (int V_0, //x1 string V_1, //y1 int V_2, //x2 string V_3, //y2 string V_4, //y3 int V_5, //x3 string V_6, //y4 int V_7) //x4 IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldc.i4.1 IL_0003: stloc.0 IL_0004: ldstr ""hello"" IL_0009: stloc.1 IL_000a: ldloca.s V_0 IL_000c: call ""string int.ToString()"" IL_0011: ldstr "" "" IL_0016: ldloc.1 IL_0017: call ""string string.Concat(string, string, string)"" IL_001c: call ""void System.Console.WriteLine(string)"" IL_0021: ldc.i4.1 IL_0022: stloc.2 IL_0023: ldstr ""hello"" IL_0028: stloc.3 IL_0029: ldloca.s V_2 IL_002b: call ""string int.ToString()"" IL_0030: ldstr "" "" IL_0035: ldloc.3 IL_0036: call ""string string.Concat(string, string, string)"" IL_003b: call ""void System.Console.WriteLine(string)"" IL_0040: ldstr """" IL_0045: stloc.s V_4 IL_0047: ldc.i4.1 IL_0048: stloc.s V_5 IL_004a: ldstr ""hello"" IL_004f: stloc.s V_4 IL_0051: ldloca.s V_5 IL_0053: call ""string int.ToString()"" IL_0058: ldstr "" "" IL_005d: ldloc.s V_4 IL_005f: call ""string string.Concat(string, string, string)"" IL_0064: call ""void System.Console.WriteLine(string)"" IL_0069: ldc.i4.1 IL_006a: stloc.s V_7 IL_006c: ldstr ""hello"" IL_0071: stloc.s V_6 IL_0073: ldloca.s V_7 IL_0075: call ""string int.ToString()"" IL_007a: ldstr "" "" IL_007f: ldloc.s V_6 IL_0081: call ""string string.Concat(string, string, string)"" IL_0086: call ""void System.Console.WriteLine(string)"" IL_008b: ret }"); } [Fact] public void MixedDeclarationAndAssignmentCSharpNine() { string source = @" class Program { static void Main() { int x1; (x1, string y1) = new A(); string y2; (int x2, y2) = new A(); bool z3; (int x3, (string y3, z3)) = new B(); int x4; (x4, var (y4, z4)) = new B(); } } class A { public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } class B { public void Deconstruct(out int a, out (string b, bool c) tuple) { a = 1; tuple = (""hello"", true); } } "; CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (7,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (x1, string y1) = new A(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(x1, string y1) = new A()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(7, 9), // (9,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (int x2, y2) = new A(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int x2, y2) = new A()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(9, 9), // (11,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (int x3, (string y3, z3)) = new B(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int x3, (string y3, z3)) = new B()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(11, 9), // (13,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (x4, var (y4, z4)) = new B(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(x4, var (y4, z4)) = new B()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(13, 9)); } [Fact] public void NestedMixedDeclarationAndAssignmentPermutations() { string source = @" class C { static void Main() { int x1; string y1; (x1, (y1, var z1)) = new C(); System.Console.WriteLine(x1 + "" "" + y1 + "" "" + z1); int x2; bool z2; (x2, (var y2, z2)) = new C(); System.Console.WriteLine(x2 + "" "" + y2 + "" "" + z2); string y3; bool z3; (var x3, (y3, z3)) = new C(); System.Console.WriteLine(x3 + "" "" + y3 + "" "" + z3); bool z4; (var x4, (var y4, z4)) = new C(); System.Console.WriteLine(x4 + "" "" + y4 + "" "" + z4); string y5; (var x5, (y5, var z5)) = new C(); System.Console.WriteLine(x5 + "" "" + y5 + "" "" + z5); int x6; (x6, (var y6, var z6)) = new C(); System.Console.WriteLine(x6 + "" "" + y6 + "" "" + z6); int x7; (x7, var (y7, z7)) = new C(); System.Console.WriteLine(x7 + "" "" + y7 + "" "" + z7); } public void Deconstruct(out int a, out (string a, bool b) b) { a = 1; b = (""hello"", true); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello True 1 hello True 1 hello True 1 hello True 1 hello True 1 hello True 1 hello True"); comp.VerifyDiagnostics(); } [Fact] public void MixedDeclarationAndAssignmentUseBeforeDeclaration() { string source = @" class Program { static void Main() { (x1, string y1) = new A(); int x1; (int x2, y2) = new A(); string y2; (int x3, (string y3, z3)) = new B(); bool z3; (x4, var (y4, z4)) = new B(); int x4; } } class A { public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } class B { public void Deconstruct(out int a, out (string b, bool c) tuple) { a = 1; tuple = (""hello"", true); } } "; CreateCompilation(source, parseOptions: TestOptions.RegularPreview) .VerifyDiagnostics( // (6,10): error CS0841: Cannot use local variable 'x1' before it is declared // (x1, string y1) = new A(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1", isSuppressed: false).WithArguments("x1").WithLocation(6, 10), // (8,18): error CS0841: Cannot use local variable 'y2' before it is declared // (int x2, y2) = new A(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y2", isSuppressed: false).WithArguments("y2").WithLocation(8, 18), // (10,30): error CS0841: Cannot use local variable 'z3' before it is declared // (int x3, (string y3, z3)) = new B(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "z3", isSuppressed: false).WithArguments("z3").WithLocation(10, 30), // (12,10): error CS0841: Cannot use local variable 'x4' before it is declared // (x4, var (y4, z4)) = new B(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4", isSuppressed: false).WithArguments("x4").WithLocation(12, 10)); } [Fact] public void MixedDeclarationAndAssignmentUseDeclaredVariableInAssignment() { string source = @" class Program { static void Main() { (var x1, x1) = new A(); (x2, var x2) = new A(); (var x3, (var y3, x3)) = new B(); (x4, (var y4, var x4)) = new B(); } } class A { public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } class B { public void Deconstruct(out int a, out (string b, bool c) tuple) { a = 1; tuple = (""hello"", true); } } "; CreateCompilation(source, parseOptions: TestOptions.RegularPreview) .VerifyDiagnostics( // (6,18): error CS0841: Cannot use local variable 'x1' before it is declared // (var x1, x1) = new A(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 18), // (7,10): error CS0841: Cannot use local variable 'x2' before it is declared // (x2, var x2) = new A(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(7, 10), // (8,27): error CS0841: Cannot use local variable 'x3' before it is declared // (var x3, (var y3, x3)) = new B(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x3").WithArguments("x3").WithLocation(8, 27), // (9,10): error CS0841: Cannot use local variable 'x4' before it is declared // (x4, (var y4, var x4)) = new B(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 10)); } } }
-1
dotnet/roslyn
55,066
Correctly set IsRetargetable for source assemblies
Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
333fred
2021-07-23T00:55:50Z
2021-07-24T00:08:23Z
a3b5d0f87fbdceadf6d3d1b024aca4736e3e079e
c58fbd573ea1ca0273ef3878782baab73d5201c8
Correctly set IsRetargetable for source assemblies. Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
./src/EditorFeatures/Core.Wpf/Interactive/InteractiveDocumentNavigationService.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.Threading; using Microsoft.CodeAnalysis.Editor.Interactive; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Implementation.Interactive { internal sealed class InteractiveDocumentNavigationService : IDocumentNavigationService { public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) => true; public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) => false; public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken) => false; public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, bool allowInvalidSpan, CancellationToken cancellationToken) { if (workspace is not InteractiveWindowWorkspace interactiveWorkspace) { Debug.Fail("InteractiveDocumentNavigationService called with incorrect workspace!"); return false; } var textView = interactiveWorkspace.Window.TextView; var document = interactiveWorkspace.CurrentSolution.GetDocument(documentId); var textSnapshot = document.GetTextSynchronously(cancellationToken).FindCorrespondingEditorTextSnapshot(); if (textSnapshot == null) { return false; } var snapshotSpan = new SnapshotSpan(textSnapshot, textSpan.Start, textSpan.Length); var virtualSnapshotSpan = new VirtualSnapshotSpan(snapshotSpan); if (!textView.TryGetSurfaceBufferSpan(virtualSnapshotSpan, out var surfaceBufferSpan)) { return false; } textView.Selection.Select(surfaceBufferSpan.Start, surfaceBufferSpan.End); textView.ViewScroller.EnsureSpanVisible(surfaceBufferSpan.SnapshotSpan, EnsureSpanVisibleOptions.AlwaysCenter); // Moving the caret must be the last operation involving surfaceBufferSpan because // it might update the version number of textView.TextSnapshot (VB does line commit // when the caret leaves a line which might cause pretty listing), which must be // equal to surfaceBufferSpan.SnapshotSpan.Snapshot's version number. textView.Caret.MoveTo(surfaceBufferSpan.Start); textView.VisualElement.Focus(); return true; } public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options, CancellationToken cancellationToken) => throw new NotSupportedException(); public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options, CancellationToken cancellationToken) => throw new NotSupportedException(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Editor.Interactive; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Implementation.Interactive { internal sealed class InteractiveDocumentNavigationService : IDocumentNavigationService { public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) => true; public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) => false; public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken) => false; public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, bool allowInvalidSpan, CancellationToken cancellationToken) { if (workspace is not InteractiveWindowWorkspace interactiveWorkspace) { Debug.Fail("InteractiveDocumentNavigationService called with incorrect workspace!"); return false; } var textView = interactiveWorkspace.Window.TextView; var document = interactiveWorkspace.CurrentSolution.GetDocument(documentId); var textSnapshot = document.GetTextSynchronously(cancellationToken).FindCorrespondingEditorTextSnapshot(); if (textSnapshot == null) { return false; } var snapshotSpan = new SnapshotSpan(textSnapshot, textSpan.Start, textSpan.Length); var virtualSnapshotSpan = new VirtualSnapshotSpan(snapshotSpan); if (!textView.TryGetSurfaceBufferSpan(virtualSnapshotSpan, out var surfaceBufferSpan)) { return false; } textView.Selection.Select(surfaceBufferSpan.Start, surfaceBufferSpan.End); textView.ViewScroller.EnsureSpanVisible(surfaceBufferSpan.SnapshotSpan, EnsureSpanVisibleOptions.AlwaysCenter); // Moving the caret must be the last operation involving surfaceBufferSpan because // it might update the version number of textView.TextSnapshot (VB does line commit // when the caret leaves a line which might cause pretty listing), which must be // equal to surfaceBufferSpan.SnapshotSpan.Snapshot's version number. textView.Caret.MoveTo(surfaceBufferSpan.Start); textView.VisualElement.Focus(); return true; } public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options, CancellationToken cancellationToken) => throw new NotSupportedException(); public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options, CancellationToken cancellationToken) => throw new NotSupportedException(); } }
-1
dotnet/roslyn
55,066
Correctly set IsRetargetable for source assemblies
Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
333fred
2021-07-23T00:55:50Z
2021-07-24T00:08:23Z
a3b5d0f87fbdceadf6d3d1b024aca4736e3e079e
c58fbd573ea1ca0273ef3878782baab73d5201c8
Correctly set IsRetargetable for source assemblies. Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
./src/Compilers/Test/Resources/Core/SymbolsTests/Metadata/InvalidCharactersInAssemblyName.il
.assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly 'xx  \r \n  !"#$%&\'()*+,-./0123456789:;<=>? ' { .hash algorithm 0x00008004 .ver 1:0:0:0 } .module 'a,b.dll' .corflags 0x00000001 // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi beforefieldinit lib.Class1 extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Class1::.ctor } // end of class lib.Class1
.assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly 'xx  \r \n  !"#$%&\'()*+,-./0123456789:;<=>? ' { .hash algorithm 0x00008004 .ver 1:0:0:0 } .module 'a,b.dll' .corflags 0x00000001 // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi beforefieldinit lib.Class1 extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Class1::.ctor } // end of class lib.Class1
-1
dotnet/roslyn
55,066
Correctly set IsRetargetable for source assemblies
Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
333fred
2021-07-23T00:55:50Z
2021-07-24T00:08:23Z
a3b5d0f87fbdceadf6d3d1b024aca4736e3e079e
c58fbd573ea1ca0273ef3878782baab73d5201c8
Correctly set IsRetargetable for source assemblies. Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
./src/Compilers/Core/MSBuildTaskTests/TestUtilities/MSBuildUtil.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.Build.Framework; using Moq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests { internal static class MSBuildUtil { public static ITaskItem[] CreateTaskItems(params string[] fileNames) { return fileNames.Select(CreateTaskItem).ToArray(); } public static ITaskItem CreateTaskItem(string fileName) { var taskItem = new Mock<ITaskItem>(MockBehavior.Strict); taskItem.Setup(x => x.ItemSpec).Returns(fileName); return taskItem.Object; } public static ITaskItem CreateTaskItem(string fileName, Dictionary<string, string> metadata) { var taskItem = new Mock<ITaskItem>(MockBehavior.Strict); taskItem.Setup(x => x.ItemSpec).Returns(fileName); taskItem.Setup(x => x.GetMetadata(It.IsAny<string>())).Returns<string>(s => s switch { "FullPath" => fileName, _ => metadata.ContainsKey(s) ? metadata[s] : string.Empty }); return taskItem.Object; } } }
// Licensed to the .NET Foundation under one or more 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.Build.Framework; using Moq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests { internal static class MSBuildUtil { public static ITaskItem[] CreateTaskItems(params string[] fileNames) { return fileNames.Select(CreateTaskItem).ToArray(); } public static ITaskItem CreateTaskItem(string fileName) { var taskItem = new Mock<ITaskItem>(MockBehavior.Strict); taskItem.Setup(x => x.ItemSpec).Returns(fileName); return taskItem.Object; } public static ITaskItem CreateTaskItem(string fileName, Dictionary<string, string> metadata) { var taskItem = new Mock<ITaskItem>(MockBehavior.Strict); taskItem.Setup(x => x.ItemSpec).Returns(fileName); taskItem.Setup(x => x.GetMetadata(It.IsAny<string>())).Returns<string>(s => s switch { "FullPath" => fileName, _ => metadata.ContainsKey(s) ? metadata[s] : string.Empty }); return taskItem.Object; } } }
-1
dotnet/roslyn
55,066
Correctly set IsRetargetable for source assemblies
Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
333fred
2021-07-23T00:55:50Z
2021-07-24T00:08:23Z
a3b5d0f87fbdceadf6d3d1b024aca4736e3e079e
c58fbd573ea1ca0273ef3878782baab73d5201c8
Correctly set IsRetargetable for source assemblies. Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
./src/VisualStudio/Core/Def/Implementation/FindReferences/Entries/DefinitionItemEntry.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.Windows.Documents; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.FindUsages { internal partial class StreamingFindUsagesPresenter { /// <summary> /// Shows a DefinitionItem as a Row in the FindReferencesWindow. Only used for /// GoToDefinition/FindImplementations. In these operations, we don't want to /// create a DefinitionBucket. So we instead just so the symbol as a normal row. /// </summary> private class DefinitionItemEntry : AbstractDocumentSpanEntry { private readonly string _projectName; public DefinitionItemEntry( AbstractTableDataSourceFindUsagesContext context, RoslynDefinitionBucket definitionBucket, string projectName, Guid projectGuid, SourceText lineText, MappedSpanResult mappedSpanResult) : base(context, definitionBucket, projectGuid, lineText, mappedSpanResult) { _projectName = projectName; } protected override string GetProjectName() => _projectName; protected override IList<Inline> CreateLineTextInlines() => DefinitionBucket.DefinitionItem.DisplayParts.ToInlines(Presenter.ClassificationFormatMap, Presenter.TypeMap); } } }
// Licensed to the .NET Foundation under one or more 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.Windows.Documents; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.FindUsages { internal partial class StreamingFindUsagesPresenter { /// <summary> /// Shows a DefinitionItem as a Row in the FindReferencesWindow. Only used for /// GoToDefinition/FindImplementations. In these operations, we don't want to /// create a DefinitionBucket. So we instead just so the symbol as a normal row. /// </summary> private class DefinitionItemEntry : AbstractDocumentSpanEntry { private readonly string _projectName; public DefinitionItemEntry( AbstractTableDataSourceFindUsagesContext context, RoslynDefinitionBucket definitionBucket, string projectName, Guid projectGuid, SourceText lineText, MappedSpanResult mappedSpanResult) : base(context, definitionBucket, projectGuid, lineText, mappedSpanResult) { _projectName = projectName; } protected override string GetProjectName() => _projectName; protected override IList<Inline> CreateLineTextInlines() => DefinitionBucket.DefinitionItem.DisplayParts.ToInlines(Presenter.ClassificationFormatMap, Presenter.TypeMap); } } }
-1
dotnet/roslyn
55,066
Correctly set IsRetargetable for source assemblies
Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
333fred
2021-07-23T00:55:50Z
2021-07-24T00:08:23Z
a3b5d0f87fbdceadf6d3d1b024aca4736e3e079e
c58fbd573ea1ca0273ef3878782baab73d5201c8
Correctly set IsRetargetable for source assemblies. Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
./src/EditorFeatures/TestUtilities/Utilities/TestEditorOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities { /// <summary> /// Mock object for editor options. /// not sure why, but Moq throw Null exception when DefaultOptions.StaticXXXField is used in Moq /// </summary> public class TestEditorOptions : IEditorOptions { public static IEditorOptions Instance = new TestEditorOptions(); private readonly bool _convertTabsToSpaces; private readonly int _tabSize; private readonly int _indentSize; public TestEditorOptions() { _convertTabsToSpaces = true; _tabSize = 4; _indentSize = 4; } public TestEditorOptions(bool convertTabsToSpaces, int tabSize, int indentSize) { _convertTabsToSpaces = convertTabsToSpaces; _tabSize = tabSize; _indentSize = indentSize; } public T GetOptionValue<T>(EditorOptionKey<T> key) { if (key.Equals(DefaultOptions.ConvertTabsToSpacesOptionId)) { return (T)(object)_convertTabsToSpaces; } else if (key.Equals(DefaultOptions.TabSizeOptionId)) { return (T)(object)_tabSize; } else if (key.Equals(DefaultOptions.IndentSizeOptionId)) { return (T)(object)_indentSize; } throw new ArgumentException("key", "unexpected key"); } #region not implemented public bool ClearOptionValue<T>(EditorOptionKey<T> key) => throw new NotImplementedException(); public bool ClearOptionValue(string optionId) => throw new NotImplementedException(); public object GetOptionValue(string optionId) => throw new NotImplementedException(); public T GetOptionValue<T>(string optionId) => throw new NotImplementedException(); public IEditorOptions GlobalOptions { get { throw new NotImplementedException(); } } public bool IsOptionDefined<T>(EditorOptionKey<T> key, bool localScopeOnly) => throw new NotImplementedException(); public bool IsOptionDefined(string optionId, bool localScopeOnly) => throw new NotImplementedException(); #pragma warning disable 67 public event EventHandler<EditorOptionChangedEventArgs> OptionChanged; public IEditorOptions Parent { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public void SetOptionValue<T>(EditorOptionKey<T> key, T value) => throw new NotImplementedException(); public void SetOptionValue(string optionId, object value) => throw new NotImplementedException(); public System.Collections.Generic.IEnumerable<EditorOptionDefinition> SupportedOptions { get { throw new NotImplementedException(); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities { /// <summary> /// Mock object for editor options. /// not sure why, but Moq throw Null exception when DefaultOptions.StaticXXXField is used in Moq /// </summary> public class TestEditorOptions : IEditorOptions { public static IEditorOptions Instance = new TestEditorOptions(); private readonly bool _convertTabsToSpaces; private readonly int _tabSize; private readonly int _indentSize; public TestEditorOptions() { _convertTabsToSpaces = true; _tabSize = 4; _indentSize = 4; } public TestEditorOptions(bool convertTabsToSpaces, int tabSize, int indentSize) { _convertTabsToSpaces = convertTabsToSpaces; _tabSize = tabSize; _indentSize = indentSize; } public T GetOptionValue<T>(EditorOptionKey<T> key) { if (key.Equals(DefaultOptions.ConvertTabsToSpacesOptionId)) { return (T)(object)_convertTabsToSpaces; } else if (key.Equals(DefaultOptions.TabSizeOptionId)) { return (T)(object)_tabSize; } else if (key.Equals(DefaultOptions.IndentSizeOptionId)) { return (T)(object)_indentSize; } throw new ArgumentException("key", "unexpected key"); } #region not implemented public bool ClearOptionValue<T>(EditorOptionKey<T> key) => throw new NotImplementedException(); public bool ClearOptionValue(string optionId) => throw new NotImplementedException(); public object GetOptionValue(string optionId) => throw new NotImplementedException(); public T GetOptionValue<T>(string optionId) => throw new NotImplementedException(); public IEditorOptions GlobalOptions { get { throw new NotImplementedException(); } } public bool IsOptionDefined<T>(EditorOptionKey<T> key, bool localScopeOnly) => throw new NotImplementedException(); public bool IsOptionDefined(string optionId, bool localScopeOnly) => throw new NotImplementedException(); #pragma warning disable 67 public event EventHandler<EditorOptionChangedEventArgs> OptionChanged; public IEditorOptions Parent { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public void SetOptionValue<T>(EditorOptionKey<T> key, T value) => throw new NotImplementedException(); public void SetOptionValue(string optionId, object value) => throw new NotImplementedException(); public System.Collections.Generic.IEnumerable<EditorOptionDefinition> SupportedOptions { get { throw new NotImplementedException(); } } #endregion } }
-1
dotnet/roslyn
55,066
Correctly set IsRetargetable for source assemblies
Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
333fred
2021-07-23T00:55:50Z
2021-07-24T00:08:23Z
a3b5d0f87fbdceadf6d3d1b024aca4736e3e079e
c58fbd573ea1ca0273ef3878782baab73d5201c8
Correctly set IsRetargetable for source assemblies. Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
./src/EditorFeatures/Test/CodeGeneration/ExpressionPrecedenceGenerationTests.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.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration { [Trait(Traits.Feature, Traits.Features.CodeGeneration)] public class ExpressionPrecedenceGenerationTests : AbstractCodeGenerationTests { [Fact] public void TestAddMultiplyPrecedence1() { Test( f => f.MultiplyExpression( f.AddExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) + (2)) * (3)", csSimple: "(1 + 2) * 3", vb: "((1) + (2)) * (3)", vbSimple: "(1 + 2) * 3"); } [Fact] public void TestAddMultiplyPrecedence2() { Test( f => f.AddExpression( f.MultiplyExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) * (2)) + (3)", csSimple: "1 * 2 + 3", vb: "((1) * (2)) + (3)", vbSimple: "1 * 2 + 3"); } [Fact] public void TestAddMultiplyPrecedence3() { Test( f => f.MultiplyExpression( f.LiteralExpression(1), f.AddExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) * ((2) + (3))", csSimple: "1 * (2 + 3)", vb: "(1) * ((2) + (3))", vbSimple: "1 * (2 + 3)"); } [Fact] public void TestAddMultiplyPrecedence4() { Test( f => f.AddExpression( f.LiteralExpression(1), f.MultiplyExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) + ((2) * (3))", csSimple: "1 + 2 * 3", vb: "(1) + ((2) * (3))", vbSimple: "1 + 2 * 3"); } [Fact] public void TestBitwiseAndOrPrecedence1() { Test( f => f.BitwiseAndExpression( f.BitwiseOrExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) | (2)) & (3)", csSimple: "(1 | 2) & 3", vb: "((1) Or (2)) And (3)", vbSimple: "(1 Or 2) And 3"); } [Fact] public void TestBitwiseAndOrPrecedence2() { Test( f => f.BitwiseOrExpression( f.BitwiseAndExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) & (2)) | (3)", csSimple: "1 & 2 | 3", vb: "((1) And (2)) Or (3)", vbSimple: "1 And 2 Or 3"); } [Fact] public void TestBitwiseAndOrPrecedence3() { Test( f => f.BitwiseAndExpression( f.LiteralExpression(1), f.BitwiseOrExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) & ((2) | (3))", csSimple: "1 & (2 | 3)", vb: "(1) And ((2) Or (3))", vbSimple: "1 And (2 Or 3)"); } [Fact] public void TestBitwiseAndOrPrecedence4() { Test( f => f.BitwiseOrExpression( f.LiteralExpression(1), f.BitwiseAndExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) | ((2) & (3))", csSimple: "1 | 2 & 3", vb: "(1) Or ((2) And (3))", vbSimple: "1 Or 2 And 3"); } [Fact] public void TestLogicalAndOrPrecedence1() { Test( f => f.LogicalAndExpression( f.LogicalOrExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) || (2)) && (3)", csSimple: "(1 || 2) && 3", vb: "((1) OrElse (2)) AndAlso (3)", vbSimple: "(1 OrElse 2) AndAlso 3"); } [Fact] public void TestLogicalAndOrPrecedence2() { Test( f => f.LogicalOrExpression( f.LogicalAndExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) && (2)) || (3)", csSimple: "1 && 2 || 3", vb: "((1) AndAlso (2)) OrElse (3)", vbSimple: "1 AndAlso 2 OrElse 3"); } [Fact] public void TestLogicalAndOrPrecedence3() { Test( f => f.LogicalAndExpression( f.LiteralExpression(1), f.LogicalOrExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) && ((2) || (3))", csSimple: "1 && (2 || 3)", vb: "(1) AndAlso ((2) OrElse (3))", vbSimple: "1 AndAlso (2 OrElse 3)"); } [Fact] public void TestLogicalAndOrPrecedence4() { Test( f => f.LogicalOrExpression( f.LiteralExpression(1), f.LogicalAndExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) || ((2) && (3))", csSimple: "1 || 2 && 3", vb: "(1) OrElse ((2) AndAlso (3))", vbSimple: "1 OrElse 2 AndAlso 3"); } [Fact] public void TestMemberAccessOffOfAdd1() { Test( f => f.MemberAccessExpression( f.AddExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.IdentifierName("M")), cs: "((1) + (2)).M", csSimple: "(1 + 2).M", vb: "((1) + (2)).M", vbSimple: "(1 + 2).M"); } [Fact] public void TestConditionalExpression1() { Test( f => f.ConditionalExpression( f.AssignmentStatement( f.IdentifierName("E1"), f.IdentifierName("E2")), f.IdentifierName("T"), f.IdentifierName("F")), cs: "(E1 = (E2)) ? (T) : (F)", csSimple: "(E1 = E2) ? T : F", vb: null, vbSimple: null); } [Fact] public void TestConditionalExpression2() { Test( f => f.AddExpression( f.ConditionalExpression( f.IdentifierName("E1"), f.IdentifierName("T1"), f.IdentifierName("F1")), f.ConditionalExpression( f.IdentifierName("E2"), f.IdentifierName("T2"), f.IdentifierName("F2"))), cs: "((E1) ? (T1) : (F1)) + ((E2) ? (T2) : (F2))", csSimple: "(E1 ? T1 : F1) + (E2 ? T2 : F2)", vb: null, vbSimple: null); } [Fact] public void TestMemberAccessOffOfElementAccess() { Test( f => f.ElementAccessExpression( f.AddExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.Argument(f.IdentifierName("M"))), cs: "((1) + (2))[M]", csSimple: "(1 + 2)[M]", vb: "((1) + (2))(M)", vbSimple: "(1 + 2)(M)"); } [Fact] public void TestMemberAccessOffOfIsExpression() { Test( f => f.MemberAccessExpression( f.IsTypeExpression( f.IdentifierName("a"), CreateClass("SomeType")), f.IdentifierName("M")), cs: "((a) is SomeType).M", csSimple: "(a is SomeType).M", vb: "(TypeOf (a) Is SomeType).M", vbSimple: "(TypeOf a Is SomeType).M"); } [Fact] public void TestIsOfMemberAccessExpression() { Test( f => f.IsTypeExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M")), CreateClass("SomeType")), cs: "(a.M) is SomeType", csSimple: "a.M is SomeType", vb: "TypeOf (a.M) Is SomeType", vbSimple: "TypeOf a.M Is SomeType"); } [Fact] public void TestMemberAccessOffOfAsExpression() { Test( f => f.MemberAccessExpression( f.TryCastExpression( f.IdentifierName("a"), CreateClass("SomeType")), f.IdentifierName("M")), cs: "((a) as SomeType).M", csSimple: "(a as SomeType).M", vb: "(TryCast(a, SomeType)).M", vbSimple: "TryCast(a, SomeType).M"); } [Fact] public void TestAsOfMemberAccessExpression() { Test( f => f.TryCastExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M")), CreateClass("SomeType")), cs: "(a.M) as SomeType", csSimple: "a.M as SomeType", vb: "TryCast(a.M, SomeType)", vbSimple: "TryCast(a.M, SomeType)"); } [Fact] public void TestMemberAccessOffOfNotExpression() { Test( f => f.MemberAccessExpression( f.LogicalNotExpression( f.IdentifierName("a")), f.IdentifierName("M")), cs: "(!(a)).M", csSimple: "(!a).M", vb: "(Not (a)).M", vbSimple: "(Not a).M"); } [Fact] public void TestNotOfMemberAccessExpression() { Test( f => f.LogicalNotExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M"))), cs: "!(a.M)", csSimple: "!a.M", vb: "Not (a.M)", vbSimple: "Not a.M"); } [Fact] public void TestMemberAccessOffOfCastExpression() { Test( f => f.MemberAccessExpression( f.CastExpression( CreateClass("SomeType"), f.IdentifierName("a")), f.IdentifierName("M")), cs: "((SomeType)(a)).M", csSimple: "((SomeType)a).M", vb: "(DirectCast(a, SomeType)).M", vbSimple: "DirectCast(a, SomeType).M"); } [Fact] public void TestCastOfAddExpression() { Test( f => f.CastExpression( CreateClass("SomeType"), f.AddExpression( f.IdentifierName("a"), f.IdentifierName("b"))), cs: "(SomeType)((a) + (b))", csSimple: "(SomeType)(a + b)", vb: "DirectCast((a) + (b), SomeType)", vbSimple: "DirectCast(a + b, SomeType)"); } [Fact] public void TestNegateOfAddExpression() { Test( f => f.NegateExpression( f.AddExpression( f.IdentifierName("a"), f.IdentifierName("b"))), cs: "-((a) + (b))", csSimple: "-(a + b)", vb: "-((a) + (b))", vbSimple: "-(a + b)"); } [Fact] public void TestMemberAccessOffOfNegate() { Test( f => f.MemberAccessExpression( f.NegateExpression( f.IdentifierName("a")), f.IdentifierName("M")), cs: "(-(a)).M", csSimple: "(-a).M", vb: "(-(a)).M", vbSimple: "(-a).M"); } [Fact] public void TestNegateOfMemberAccess() { Test(f => f.NegateExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M"))), cs: "-(a.M)", csSimple: "-a.M", vb: "-(a.M)", vbSimple: "-a.M"); } } }
// Licensed to the .NET Foundation under one or more 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.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration { [Trait(Traits.Feature, Traits.Features.CodeGeneration)] public class ExpressionPrecedenceGenerationTests : AbstractCodeGenerationTests { [Fact] public void TestAddMultiplyPrecedence1() { Test( f => f.MultiplyExpression( f.AddExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) + (2)) * (3)", csSimple: "(1 + 2) * 3", vb: "((1) + (2)) * (3)", vbSimple: "(1 + 2) * 3"); } [Fact] public void TestAddMultiplyPrecedence2() { Test( f => f.AddExpression( f.MultiplyExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) * (2)) + (3)", csSimple: "1 * 2 + 3", vb: "((1) * (2)) + (3)", vbSimple: "1 * 2 + 3"); } [Fact] public void TestAddMultiplyPrecedence3() { Test( f => f.MultiplyExpression( f.LiteralExpression(1), f.AddExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) * ((2) + (3))", csSimple: "1 * (2 + 3)", vb: "(1) * ((2) + (3))", vbSimple: "1 * (2 + 3)"); } [Fact] public void TestAddMultiplyPrecedence4() { Test( f => f.AddExpression( f.LiteralExpression(1), f.MultiplyExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) + ((2) * (3))", csSimple: "1 + 2 * 3", vb: "(1) + ((2) * (3))", vbSimple: "1 + 2 * 3"); } [Fact] public void TestBitwiseAndOrPrecedence1() { Test( f => f.BitwiseAndExpression( f.BitwiseOrExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) | (2)) & (3)", csSimple: "(1 | 2) & 3", vb: "((1) Or (2)) And (3)", vbSimple: "(1 Or 2) And 3"); } [Fact] public void TestBitwiseAndOrPrecedence2() { Test( f => f.BitwiseOrExpression( f.BitwiseAndExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) & (2)) | (3)", csSimple: "1 & 2 | 3", vb: "((1) And (2)) Or (3)", vbSimple: "1 And 2 Or 3"); } [Fact] public void TestBitwiseAndOrPrecedence3() { Test( f => f.BitwiseAndExpression( f.LiteralExpression(1), f.BitwiseOrExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) & ((2) | (3))", csSimple: "1 & (2 | 3)", vb: "(1) And ((2) Or (3))", vbSimple: "1 And (2 Or 3)"); } [Fact] public void TestBitwiseAndOrPrecedence4() { Test( f => f.BitwiseOrExpression( f.LiteralExpression(1), f.BitwiseAndExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) | ((2) & (3))", csSimple: "1 | 2 & 3", vb: "(1) Or ((2) And (3))", vbSimple: "1 Or 2 And 3"); } [Fact] public void TestLogicalAndOrPrecedence1() { Test( f => f.LogicalAndExpression( f.LogicalOrExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) || (2)) && (3)", csSimple: "(1 || 2) && 3", vb: "((1) OrElse (2)) AndAlso (3)", vbSimple: "(1 OrElse 2) AndAlso 3"); } [Fact] public void TestLogicalAndOrPrecedence2() { Test( f => f.LogicalOrExpression( f.LogicalAndExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) && (2)) || (3)", csSimple: "1 && 2 || 3", vb: "((1) AndAlso (2)) OrElse (3)", vbSimple: "1 AndAlso 2 OrElse 3"); } [Fact] public void TestLogicalAndOrPrecedence3() { Test( f => f.LogicalAndExpression( f.LiteralExpression(1), f.LogicalOrExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) && ((2) || (3))", csSimple: "1 && (2 || 3)", vb: "(1) AndAlso ((2) OrElse (3))", vbSimple: "1 AndAlso (2 OrElse 3)"); } [Fact] public void TestLogicalAndOrPrecedence4() { Test( f => f.LogicalOrExpression( f.LiteralExpression(1), f.LogicalAndExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) || ((2) && (3))", csSimple: "1 || 2 && 3", vb: "(1) OrElse ((2) AndAlso (3))", vbSimple: "1 OrElse 2 AndAlso 3"); } [Fact] public void TestMemberAccessOffOfAdd1() { Test( f => f.MemberAccessExpression( f.AddExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.IdentifierName("M")), cs: "((1) + (2)).M", csSimple: "(1 + 2).M", vb: "((1) + (2)).M", vbSimple: "(1 + 2).M"); } [Fact] public void TestConditionalExpression1() { Test( f => f.ConditionalExpression( f.AssignmentStatement( f.IdentifierName("E1"), f.IdentifierName("E2")), f.IdentifierName("T"), f.IdentifierName("F")), cs: "(E1 = (E2)) ? (T) : (F)", csSimple: "(E1 = E2) ? T : F", vb: null, vbSimple: null); } [Fact] public void TestConditionalExpression2() { Test( f => f.AddExpression( f.ConditionalExpression( f.IdentifierName("E1"), f.IdentifierName("T1"), f.IdentifierName("F1")), f.ConditionalExpression( f.IdentifierName("E2"), f.IdentifierName("T2"), f.IdentifierName("F2"))), cs: "((E1) ? (T1) : (F1)) + ((E2) ? (T2) : (F2))", csSimple: "(E1 ? T1 : F1) + (E2 ? T2 : F2)", vb: null, vbSimple: null); } [Fact] public void TestMemberAccessOffOfElementAccess() { Test( f => f.ElementAccessExpression( f.AddExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.Argument(f.IdentifierName("M"))), cs: "((1) + (2))[M]", csSimple: "(1 + 2)[M]", vb: "((1) + (2))(M)", vbSimple: "(1 + 2)(M)"); } [Fact] public void TestMemberAccessOffOfIsExpression() { Test( f => f.MemberAccessExpression( f.IsTypeExpression( f.IdentifierName("a"), CreateClass("SomeType")), f.IdentifierName("M")), cs: "((a) is SomeType).M", csSimple: "(a is SomeType).M", vb: "(TypeOf (a) Is SomeType).M", vbSimple: "(TypeOf a Is SomeType).M"); } [Fact] public void TestIsOfMemberAccessExpression() { Test( f => f.IsTypeExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M")), CreateClass("SomeType")), cs: "(a.M) is SomeType", csSimple: "a.M is SomeType", vb: "TypeOf (a.M) Is SomeType", vbSimple: "TypeOf a.M Is SomeType"); } [Fact] public void TestMemberAccessOffOfAsExpression() { Test( f => f.MemberAccessExpression( f.TryCastExpression( f.IdentifierName("a"), CreateClass("SomeType")), f.IdentifierName("M")), cs: "((a) as SomeType).M", csSimple: "(a as SomeType).M", vb: "(TryCast(a, SomeType)).M", vbSimple: "TryCast(a, SomeType).M"); } [Fact] public void TestAsOfMemberAccessExpression() { Test( f => f.TryCastExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M")), CreateClass("SomeType")), cs: "(a.M) as SomeType", csSimple: "a.M as SomeType", vb: "TryCast(a.M, SomeType)", vbSimple: "TryCast(a.M, SomeType)"); } [Fact] public void TestMemberAccessOffOfNotExpression() { Test( f => f.MemberAccessExpression( f.LogicalNotExpression( f.IdentifierName("a")), f.IdentifierName("M")), cs: "(!(a)).M", csSimple: "(!a).M", vb: "(Not (a)).M", vbSimple: "(Not a).M"); } [Fact] public void TestNotOfMemberAccessExpression() { Test( f => f.LogicalNotExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M"))), cs: "!(a.M)", csSimple: "!a.M", vb: "Not (a.M)", vbSimple: "Not a.M"); } [Fact] public void TestMemberAccessOffOfCastExpression() { Test( f => f.MemberAccessExpression( f.CastExpression( CreateClass("SomeType"), f.IdentifierName("a")), f.IdentifierName("M")), cs: "((SomeType)(a)).M", csSimple: "((SomeType)a).M", vb: "(DirectCast(a, SomeType)).M", vbSimple: "DirectCast(a, SomeType).M"); } [Fact] public void TestCastOfAddExpression() { Test( f => f.CastExpression( CreateClass("SomeType"), f.AddExpression( f.IdentifierName("a"), f.IdentifierName("b"))), cs: "(SomeType)((a) + (b))", csSimple: "(SomeType)(a + b)", vb: "DirectCast((a) + (b), SomeType)", vbSimple: "DirectCast(a + b, SomeType)"); } [Fact] public void TestNegateOfAddExpression() { Test( f => f.NegateExpression( f.AddExpression( f.IdentifierName("a"), f.IdentifierName("b"))), cs: "-((a) + (b))", csSimple: "-(a + b)", vb: "-((a) + (b))", vbSimple: "-(a + b)"); } [Fact] public void TestMemberAccessOffOfNegate() { Test( f => f.MemberAccessExpression( f.NegateExpression( f.IdentifierName("a")), f.IdentifierName("M")), cs: "(-(a)).M", csSimple: "(-a).M", vb: "(-(a)).M", vbSimple: "(-a).M"); } [Fact] public void TestNegateOfMemberAccess() { Test(f => f.NegateExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M"))), cs: "-(a.M)", csSimple: "-a.M", vb: "-(a.M)", vbSimple: "-a.M"); } } }
-1
dotnet/roslyn
55,066
Correctly set IsRetargetable for source assemblies
Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
333fred
2021-07-23T00:55:50Z
2021-07-24T00:08:23Z
a3b5d0f87fbdceadf6d3d1b024aca4736e3e079e
c58fbd573ea1ca0273ef3878782baab73d5201c8
Correctly set IsRetargetable for source assemblies. Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
./src/ExpressionEvaluator/Core/Source/FunctionResolver/FunctionResolverBase.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 System; using System.Collections.Generic; using System.Reflection.Metadata; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal abstract class FunctionResolverBase<TProcess, TModule, TRequest> where TProcess : class where TModule : class where TRequest : class { internal abstract bool ShouldEnableFunctionResolver(TProcess process); internal abstract IEnumerable<TModule> GetAllModules(TProcess process); internal abstract string GetModuleName(TModule module); internal abstract MetadataReader GetModuleMetadata(TModule module); internal abstract TRequest[] GetRequests(TProcess process); internal abstract string GetRequestModuleName(TRequest request); internal abstract RequestSignature GetParsedSignature(TRequest request); internal abstract bool IgnoreCase { get; } internal abstract Guid GetLanguageId(TRequest request); internal abstract Guid LanguageId { get; } internal void EnableResolution(TProcess process, TRequest request, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { if (!ShouldHandleRequest(request)) { return; } var moduleName = GetRequestModuleName(request); var signature = GetParsedSignature(request); if (signature == null) { return; } bool checkEnabled = true; foreach (var module in GetAllModules(process)) { if (checkEnabled) { if (!ShouldEnableFunctionResolver(process)) { return; } checkEnabled = false; } if (!ShouldModuleHandleRequest(module, moduleName)) { continue; } var reader = GetModuleMetadata(module); if (reader == null) { continue; } var resolver = CreateMetadataResolver(process, module, reader, onFunctionResolved); resolver.Resolve(request, signature); } } internal void OnModuleLoad(TProcess process, TModule module, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { if (!ShouldEnableFunctionResolver(process)) { return; } MetadataResolver<TProcess, TModule, TRequest> resolver = null; var requests = GetRequests(process); foreach (var request in requests) { if (!ShouldHandleRequest(request)) { continue; } var moduleName = GetRequestModuleName(request); if (!ShouldModuleHandleRequest(module, moduleName)) { continue; } var signature = GetParsedSignature(request); if (signature == null) { continue; } if (resolver == null) { var reader = GetModuleMetadata(module); if (reader == null) { return; } resolver = CreateMetadataResolver(process, module, reader, onFunctionResolved); } resolver.Resolve(request, signature); } } private MetadataResolver<TProcess, TModule, TRequest> CreateMetadataResolver( TProcess process, TModule module, MetadataReader reader, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { return new MetadataResolver<TProcess, TModule, TRequest>(process, module, reader, IgnoreCase, onFunctionResolved); } private bool ShouldHandleRequest(TRequest request) { var languageId = GetLanguageId(request); // Handle requests with no language id, a matching language id, // or causality breakpoint requests (debugging web services). return languageId == Guid.Empty || languageId == LanguageId || languageId == DkmLanguageId.CausalityBreakpoint; } private bool ShouldModuleHandleRequest(TModule module, string moduleName) { if (string.IsNullOrEmpty(moduleName)) { return true; } var name = GetModuleName(module); return moduleName.Equals(name, StringComparison.OrdinalIgnoreCase); } } }
// Licensed to the .NET Foundation under one or more 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 System; using System.Collections.Generic; using System.Reflection.Metadata; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal abstract class FunctionResolverBase<TProcess, TModule, TRequest> where TProcess : class where TModule : class where TRequest : class { internal abstract bool ShouldEnableFunctionResolver(TProcess process); internal abstract IEnumerable<TModule> GetAllModules(TProcess process); internal abstract string GetModuleName(TModule module); internal abstract MetadataReader GetModuleMetadata(TModule module); internal abstract TRequest[] GetRequests(TProcess process); internal abstract string GetRequestModuleName(TRequest request); internal abstract RequestSignature GetParsedSignature(TRequest request); internal abstract bool IgnoreCase { get; } internal abstract Guid GetLanguageId(TRequest request); internal abstract Guid LanguageId { get; } internal void EnableResolution(TProcess process, TRequest request, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { if (!ShouldHandleRequest(request)) { return; } var moduleName = GetRequestModuleName(request); var signature = GetParsedSignature(request); if (signature == null) { return; } bool checkEnabled = true; foreach (var module in GetAllModules(process)) { if (checkEnabled) { if (!ShouldEnableFunctionResolver(process)) { return; } checkEnabled = false; } if (!ShouldModuleHandleRequest(module, moduleName)) { continue; } var reader = GetModuleMetadata(module); if (reader == null) { continue; } var resolver = CreateMetadataResolver(process, module, reader, onFunctionResolved); resolver.Resolve(request, signature); } } internal void OnModuleLoad(TProcess process, TModule module, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { if (!ShouldEnableFunctionResolver(process)) { return; } MetadataResolver<TProcess, TModule, TRequest> resolver = null; var requests = GetRequests(process); foreach (var request in requests) { if (!ShouldHandleRequest(request)) { continue; } var moduleName = GetRequestModuleName(request); if (!ShouldModuleHandleRequest(module, moduleName)) { continue; } var signature = GetParsedSignature(request); if (signature == null) { continue; } if (resolver == null) { var reader = GetModuleMetadata(module); if (reader == null) { return; } resolver = CreateMetadataResolver(process, module, reader, onFunctionResolved); } resolver.Resolve(request, signature); } } private MetadataResolver<TProcess, TModule, TRequest> CreateMetadataResolver( TProcess process, TModule module, MetadataReader reader, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { return new MetadataResolver<TProcess, TModule, TRequest>(process, module, reader, IgnoreCase, onFunctionResolved); } private bool ShouldHandleRequest(TRequest request) { var languageId = GetLanguageId(request); // Handle requests with no language id, a matching language id, // or causality breakpoint requests (debugging web services). return languageId == Guid.Empty || languageId == LanguageId || languageId == DkmLanguageId.CausalityBreakpoint; } private bool ShouldModuleHandleRequest(TModule module, string moduleName) { if (string.IsNullOrEmpty(moduleName)) { return true; } var name = GetModuleName(module); return moduleName.Equals(name, StringComparison.OrdinalIgnoreCase); } } }
-1
dotnet/roslyn
55,066
Correctly set IsRetargetable for source assemblies
Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
333fred
2021-07-23T00:55:50Z
2021-07-24T00:08:23Z
a3b5d0f87fbdceadf6d3d1b024aca4736e3e079e
c58fbd573ea1ca0273ef3878782baab73d5201c8
Correctly set IsRetargetable for source assemblies. Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
./src/Dependencies/Collections/Internal/RoslynUnsafe.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.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.Collections.Internal { internal static unsafe class RoslynUnsafe { /// <summary> /// Returns a by-ref to type <typeparamref name="T"/> that is a null reference. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T NullRef<T>() => ref Unsafe.AsRef<T>(null); /// <summary> /// Returns if a given by-ref to type <typeparamref name="T"/> is a null reference. /// </summary> /// <remarks> /// This check is conceptually similar to <c>(void*)(&amp;source) == nullptr</c>. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNullRef<T>(ref T source) => Unsafe.AsPointer(ref source) == 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.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.Collections.Internal { internal static unsafe class RoslynUnsafe { /// <summary> /// Returns a by-ref to type <typeparamref name="T"/> that is a null reference. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T NullRef<T>() => ref Unsafe.AsRef<T>(null); /// <summary> /// Returns if a given by-ref to type <typeparamref name="T"/> is a null reference. /// </summary> /// <remarks> /// This check is conceptually similar to <c>(void*)(&amp;source) == nullptr</c>. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNullRef<T>(ref T source) => Unsafe.AsPointer(ref source) == null; } }
-1
dotnet/roslyn
55,066
Correctly set IsRetargetable for source assemblies
Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
333fred
2021-07-23T00:55:50Z
2021-07-24T00:08:23Z
a3b5d0f87fbdceadf6d3d1b024aca4736e3e079e
c58fbd573ea1ca0273ef3878782baab73d5201c8
Correctly set IsRetargetable for source assemblies. Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/AbstractLegacyProject_IVsHierarchyEvents.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.IO; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy { internal partial class AbstractLegacyProject : IVsHierarchyEvents { private uint _hierarchyEventsCookie; private void ConnectHierarchyEvents() { Debug.Assert(!this.AreHierarchyEventsConnected, "IVsHierarchyEvents are already connected!"); if (ErrorHandler.Failed(Hierarchy.AdviseHierarchyEvents(this, out _hierarchyEventsCookie))) { Debug.Fail("Failed to connect IVsHierarchyEvents"); _hierarchyEventsCookie = 0; } } private void DisconnectHierarchyEvents() { if (this.AreHierarchyEventsConnected) { Hierarchy.UnadviseHierarchyEvents(_hierarchyEventsCookie); _hierarchyEventsCookie = 0; } } private bool AreHierarchyEventsConnected { get { return _hierarchyEventsCookie != 0; } } int IVsHierarchyEvents.OnInvalidateIcon(IntPtr hicon) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnInvalidateItems(uint itemidParent) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemAdded(uint itemidParent, uint itemidSiblingPrev, uint itemidAdded) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemDeleted(uint itemid) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemsAppended(uint itemidParent) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnPropertyChanged(uint itemid, int propid, uint flags) { if ((propid == (int)__VSHPROPID.VSHPROPID_Caption || propid == (int)__VSHPROPID.VSHPROPID_Name) && itemid == (uint)VSConstants.VSITEMID.Root) { var filePath = Hierarchy.TryGetProjectFilePath(); if (filePath != null && File.Exists(filePath)) { VisualStudioProject.FilePath = filePath; } if (Hierarchy.TryGetName(out var name)) { VisualStudioProject.DisplayName = name; } } return VSConstants.S_OK; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.IO; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy { internal partial class AbstractLegacyProject : IVsHierarchyEvents { private uint _hierarchyEventsCookie; private void ConnectHierarchyEvents() { Debug.Assert(!this.AreHierarchyEventsConnected, "IVsHierarchyEvents are already connected!"); if (ErrorHandler.Failed(Hierarchy.AdviseHierarchyEvents(this, out _hierarchyEventsCookie))) { Debug.Fail("Failed to connect IVsHierarchyEvents"); _hierarchyEventsCookie = 0; } } private void DisconnectHierarchyEvents() { if (this.AreHierarchyEventsConnected) { Hierarchy.UnadviseHierarchyEvents(_hierarchyEventsCookie); _hierarchyEventsCookie = 0; } } private bool AreHierarchyEventsConnected { get { return _hierarchyEventsCookie != 0; } } int IVsHierarchyEvents.OnInvalidateIcon(IntPtr hicon) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnInvalidateItems(uint itemidParent) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemAdded(uint itemidParent, uint itemidSiblingPrev, uint itemidAdded) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemDeleted(uint itemid) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemsAppended(uint itemidParent) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnPropertyChanged(uint itemid, int propid, uint flags) { if ((propid == (int)__VSHPROPID.VSHPROPID_Caption || propid == (int)__VSHPROPID.VSHPROPID_Name) && itemid == (uint)VSConstants.VSITEMID.Root) { var filePath = Hierarchy.TryGetProjectFilePath(); if (filePath != null && File.Exists(filePath)) { VisualStudioProject.FilePath = filePath; } if (Hierarchy.TryGetName(out var name)) { VisualStudioProject.DisplayName = name; } } return VSConstants.S_OK; } } }
-1
dotnet/roslyn
55,066
Correctly set IsRetargetable for source assemblies
Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
333fred
2021-07-23T00:55:50Z
2021-07-24T00:08:23Z
a3b5d0f87fbdceadf6d3d1b024aca4736e3e079e
c58fbd573ea1ca0273ef3878782baab73d5201c8
Correctly set IsRetargetable for source assemblies. Source assemblies weren't checking assembly flags and setting IsRetargetable, despite having already decoded all well-known attributes to find the other bits of the assembly identity. We now check and correctly set the IsRetargetable bit. Fixes https://github.com/dotnet/roslyn/issues/54836.
./src/EditorFeatures/CSharpTest/Diagnostics/PreferFrameworkType/PreferFrameworkTypeTests.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.Diagnostics.Analyzers; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.PreferFrameworkType; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.PreferFrameworkType { public partial class PreferFrameworkTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public PreferFrameworkTypeTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpPreferFrameworkTypeDiagnosticAnalyzer(), new PreferFrameworkTypeCodeFixProvider()); private readonly CodeStyleOption2<bool> onWithInfo = new CodeStyleOption2<bool>(true, NotificationOption2.Suggestion); private readonly CodeStyleOption2<bool> offWithInfo = new CodeStyleOption2<bool>(false, NotificationOption2.Suggestion); private OptionsCollection NoFrameworkType => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, onWithInfo }, }; private OptionsCollection FrameworkTypeEverywhere => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, offWithInfo }, }; private OptionsCollection FrameworkTypeInDeclaration => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, onWithInfo }, }; private OptionsCollection FrameworkTypeInMemberAccess => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, offWithInfo }, }; [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotWhenOptionsAreNotSet() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|int|] x = 1; } }", new TestParameters(options: NoFrameworkType)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnDynamic() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|dynamic|] x = 1; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnSystemVoid() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { [|void|] Method() { } }", new TestParameters(options: FrameworkTypeEverywhere)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnUserdefinedType() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|Program|] p; } }", new TestParameters(options: FrameworkTypeEverywhere)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnFrameworkType() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|Int32|] p; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnQualifiedTypeSyntax() { await TestMissingInRegularAndScriptAsync( @"class Program { void Method() { [|System.Int32|] p; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnFrameworkTypeWithNoPredefinedKeywordEquivalent() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|List|]<int> p; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnIdentifierThatIsNotTypeSyntax() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { int [|p|]; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task QualifiedReplacementWhenNoUsingFound() { var code = @"class Program { [|string|] _myfield = 5; }"; var expected = @"class Program { System.String _myfield = 5; }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task FieldDeclaration() { var code = @"using System; class Program { [|int|] _myfield; }"; var expected = @"using System; class Program { Int32 _myfield; }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task FieldDeclarationWithInitializer() { var code = @"using System; class Program { [|string|] _myfield = 5; }"; var expected = @"using System; class Program { String _myfield = 5; }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DelegateDeclaration() { var code = @"using System; class Program { public delegate [|int|] PerformCalculation(int x, int y); }"; var expected = @"using System; class Program { public delegate Int32 PerformCalculation(int x, int y); }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task PropertyDeclaration() { var code = @"using System; class Program { public [|long|] MyProperty { get; set; } }"; var expected = @"using System; class Program { public Int64 MyProperty { get; set; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task GenericPropertyDeclaration() { var code = @"using System; using System.Collections.Generic; class Program { public List<[|long|]> MyProperty { get; set; } }"; var expected = @"using System; using System.Collections.Generic; class Program { public List<Int64> MyProperty { get; set; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task QualifiedReplacementInGenericTypeParameter() { var code = @"using System.Collections.Generic; class Program { public List<[|long|]> MyProperty { get; set; } }"; var expected = @"using System.Collections.Generic; class Program { public List<System.Int64> MyProperty { get; set; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MethodDeclarationReturnType() { var code = @"using System; class Program { public [|long|] Method() { } }"; var expected = @"using System; class Program { public Int64 Method() { } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MethodDeclarationParameters() { var code = @"using System; class Program { public void Method([|double|] d) { } }"; var expected = @"using System; class Program { public void Method(Double d) { } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task GenericMethodInvocation() { var code = @"using System; class Program { public void Method<T>() { } public void Test() { Method<[|int|]>(); } }"; var expected = @"using System; class Program { public void Method<T>() { } public void Test() { Method<Int32>(); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task LocalDeclaration() { var code = @"using System; class Program { void Method() { [|int|] f = 5; } }"; var expected = @"using System; class Program { void Method() { Int32 f = 5; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MemberAccess() { var code = @"using System; class Program { void Method() { Console.Write([|int|].MaxValue); } }"; var expected = @"using System; class Program { void Method() { Console.Write(Int32.MaxValue); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MemberAccess2() { var code = @"using System; class Program { void Method() { var x = [|int|].Parse(""1""); } }"; var expected = @"using System; class Program { void Method() { var x = Int32.Parse(""1""); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DocCommentTriviaCrefExpression() { var code = @"using System; class Program { /// <see cref=""[|int|].MaxValue""/> void Method() { } }"; var expected = @"using System; class Program { /// <see cref=""Int32.MaxValue""/> void Method() { } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DefaultExpression() { var code = @"using System; class Program { void Method() { var v = default([|int|]); } }"; var expected = @"using System; class Program { void Method() { var v = default(Int32); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task TypeOfExpression() { var code = @"using System; class Program { void Method() { var v = typeof([|int|]); } }"; var expected = @"using System; class Program { void Method() { var v = typeof(Int32); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NameOfExpression() { var code = @"using System; class Program { void Method() { var v = nameof([|int|]); } }"; var expected = @"using System; class Program { void Method() { var v = nameof(Int32); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task FormalParametersWithinLambdaExression() { var code = @"using System; class Program { void Method() { Func<int, int> func3 = ([|int|] z) => z + 1; } }"; var expected = @"using System; class Program { void Method() { Func<int, int> func3 = (Int32 z) => z + 1; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DelegateMethodExpression() { var code = @"using System; class Program { void Method() { Func<int, int> func7 = delegate ([|int|] dx) { return dx + 1; }; } }"; var expected = @"using System; class Program { void Method() { Func<int, int> func7 = delegate (Int32 dx) { return dx + 1; }; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ObjectCreationExpression() { var code = @"using System; class Program { void Method() { string s2 = new [|string|]('c', 1); } }"; var expected = @"using System; class Program { void Method() { string s2 = new String('c', 1); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ArrayDeclaration() { var code = @"using System; class Program { void Method() { [|int|][] k = new int[4]; } }"; var expected = @"using System; class Program { void Method() { Int32[] k = new int[4]; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ArrayInitializer() { var code = @"using System; class Program { void Method() { int[] k = new [|int|][] { 1, 2, 3 }; } }"; var expected = @"using System; class Program { void Method() { int[] k = new Int32[] { 1, 2, 3 }; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MultiDimentionalArrayAsGenericTypeParameter() { var code = @"using System; using System.Collections.Generic; class Program { void Method() { List<[|string|][][,][,,,]> a; } }"; var expected = @"using System; using System.Collections.Generic; class Program { void Method() { List<String[][,][,,,]> a; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ForStatement() { var code = @"using System; class Program { void Method() { for ([|int|] j = 0; j < 4; j++) { } } }"; var expected = @"using System; class Program { void Method() { for (Int32 j = 0; j < 4; j++) { } } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ForeachStatement() { var code = @"using System; class Program { void Method() { foreach ([|int|] item in new int[] { 1, 2, 3 }) { } } }"; var expected = @"using System; class Program { void Method() { foreach (Int32 item in new int[] { 1, 2, 3 }) { } } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task LeadingTrivia() { var code = @"using System; class Program { void Method() { // this is a comment [|int|] x = 5; } }"; var expected = @"using System; class Program { void Method() { // this is a comment Int32 x = 5; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task TrailingTrivia() { var code = @"using System; class Program { void Method() { [|int|] /* 2 */ x = 5; } }"; var expected = @"using System; class Program { void Method() { Int32 /* 2 */ x = 5; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics.Analyzers; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.PreferFrameworkType; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.PreferFrameworkType { public partial class PreferFrameworkTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public PreferFrameworkTypeTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpPreferFrameworkTypeDiagnosticAnalyzer(), new PreferFrameworkTypeCodeFixProvider()); private readonly CodeStyleOption2<bool> onWithInfo = new CodeStyleOption2<bool>(true, NotificationOption2.Suggestion); private readonly CodeStyleOption2<bool> offWithInfo = new CodeStyleOption2<bool>(false, NotificationOption2.Suggestion); private OptionsCollection NoFrameworkType => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, onWithInfo }, }; private OptionsCollection FrameworkTypeEverywhere => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, offWithInfo }, }; private OptionsCollection FrameworkTypeInDeclaration => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, onWithInfo }, }; private OptionsCollection FrameworkTypeInMemberAccess => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, offWithInfo }, }; [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotWhenOptionsAreNotSet() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|int|] x = 1; } }", new TestParameters(options: NoFrameworkType)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnDynamic() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|dynamic|] x = 1; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnSystemVoid() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { [|void|] Method() { } }", new TestParameters(options: FrameworkTypeEverywhere)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnUserdefinedType() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|Program|] p; } }", new TestParameters(options: FrameworkTypeEverywhere)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnFrameworkType() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|Int32|] p; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnQualifiedTypeSyntax() { await TestMissingInRegularAndScriptAsync( @"class Program { void Method() { [|System.Int32|] p; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnFrameworkTypeWithNoPredefinedKeywordEquivalent() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|List|]<int> p; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnIdentifierThatIsNotTypeSyntax() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { int [|p|]; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task QualifiedReplacementWhenNoUsingFound() { var code = @"class Program { [|string|] _myfield = 5; }"; var expected = @"class Program { System.String _myfield = 5; }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task FieldDeclaration() { var code = @"using System; class Program { [|int|] _myfield; }"; var expected = @"using System; class Program { Int32 _myfield; }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task FieldDeclarationWithInitializer() { var code = @"using System; class Program { [|string|] _myfield = 5; }"; var expected = @"using System; class Program { String _myfield = 5; }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DelegateDeclaration() { var code = @"using System; class Program { public delegate [|int|] PerformCalculation(int x, int y); }"; var expected = @"using System; class Program { public delegate Int32 PerformCalculation(int x, int y); }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task PropertyDeclaration() { var code = @"using System; class Program { public [|long|] MyProperty { get; set; } }"; var expected = @"using System; class Program { public Int64 MyProperty { get; set; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task GenericPropertyDeclaration() { var code = @"using System; using System.Collections.Generic; class Program { public List<[|long|]> MyProperty { get; set; } }"; var expected = @"using System; using System.Collections.Generic; class Program { public List<Int64> MyProperty { get; set; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task QualifiedReplacementInGenericTypeParameter() { var code = @"using System.Collections.Generic; class Program { public List<[|long|]> MyProperty { get; set; } }"; var expected = @"using System.Collections.Generic; class Program { public List<System.Int64> MyProperty { get; set; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MethodDeclarationReturnType() { var code = @"using System; class Program { public [|long|] Method() { } }"; var expected = @"using System; class Program { public Int64 Method() { } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MethodDeclarationParameters() { var code = @"using System; class Program { public void Method([|double|] d) { } }"; var expected = @"using System; class Program { public void Method(Double d) { } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task GenericMethodInvocation() { var code = @"using System; class Program { public void Method<T>() { } public void Test() { Method<[|int|]>(); } }"; var expected = @"using System; class Program { public void Method<T>() { } public void Test() { Method<Int32>(); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task LocalDeclaration() { var code = @"using System; class Program { void Method() { [|int|] f = 5; } }"; var expected = @"using System; class Program { void Method() { Int32 f = 5; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MemberAccess() { var code = @"using System; class Program { void Method() { Console.Write([|int|].MaxValue); } }"; var expected = @"using System; class Program { void Method() { Console.Write(Int32.MaxValue); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MemberAccess2() { var code = @"using System; class Program { void Method() { var x = [|int|].Parse(""1""); } }"; var expected = @"using System; class Program { void Method() { var x = Int32.Parse(""1""); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DocCommentTriviaCrefExpression() { var code = @"using System; class Program { /// <see cref=""[|int|].MaxValue""/> void Method() { } }"; var expected = @"using System; class Program { /// <see cref=""Int32.MaxValue""/> void Method() { } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DefaultExpression() { var code = @"using System; class Program { void Method() { var v = default([|int|]); } }"; var expected = @"using System; class Program { void Method() { var v = default(Int32); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task TypeOfExpression() { var code = @"using System; class Program { void Method() { var v = typeof([|int|]); } }"; var expected = @"using System; class Program { void Method() { var v = typeof(Int32); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NameOfExpression() { var code = @"using System; class Program { void Method() { var v = nameof([|int|]); } }"; var expected = @"using System; class Program { void Method() { var v = nameof(Int32); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task FormalParametersWithinLambdaExression() { var code = @"using System; class Program { void Method() { Func<int, int> func3 = ([|int|] z) => z + 1; } }"; var expected = @"using System; class Program { void Method() { Func<int, int> func3 = (Int32 z) => z + 1; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DelegateMethodExpression() { var code = @"using System; class Program { void Method() { Func<int, int> func7 = delegate ([|int|] dx) { return dx + 1; }; } }"; var expected = @"using System; class Program { void Method() { Func<int, int> func7 = delegate (Int32 dx) { return dx + 1; }; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ObjectCreationExpression() { var code = @"using System; class Program { void Method() { string s2 = new [|string|]('c', 1); } }"; var expected = @"using System; class Program { void Method() { string s2 = new String('c', 1); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ArrayDeclaration() { var code = @"using System; class Program { void Method() { [|int|][] k = new int[4]; } }"; var expected = @"using System; class Program { void Method() { Int32[] k = new int[4]; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ArrayInitializer() { var code = @"using System; class Program { void Method() { int[] k = new [|int|][] { 1, 2, 3 }; } }"; var expected = @"using System; class Program { void Method() { int[] k = new Int32[] { 1, 2, 3 }; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MultiDimentionalArrayAsGenericTypeParameter() { var code = @"using System; using System.Collections.Generic; class Program { void Method() { List<[|string|][][,][,,,]> a; } }"; var expected = @"using System; using System.Collections.Generic; class Program { void Method() { List<String[][,][,,,]> a; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ForStatement() { var code = @"using System; class Program { void Method() { for ([|int|] j = 0; j < 4; j++) { } } }"; var expected = @"using System; class Program { void Method() { for (Int32 j = 0; j < 4; j++) { } } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ForeachStatement() { var code = @"using System; class Program { void Method() { foreach ([|int|] item in new int[] { 1, 2, 3 }) { } } }"; var expected = @"using System; class Program { void Method() { foreach (Int32 item in new int[] { 1, 2, 3 }) { } } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task LeadingTrivia() { var code = @"using System; class Program { void Method() { // this is a comment [|int|] x = 5; } }"; var expected = @"using System; class Program { void Method() { // this is a comment Int32 x = 5; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task TrailingTrivia() { var code = @"using System; class Program { void Method() { [|int|] /* 2 */ x = 5; } }"; var expected = @"using System; class Program { void Method() { Int32 /* 2 */ x = 5; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./eng/targets/Settings.props
<?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> <PropertyGroup> <Copyright>$(CopyrightMicrosoft)</Copyright> <PackageLicenseExpression>MIT</PackageLicenseExpression> <PackageTags>Roslyn CodeAnalysis Compiler CSharp VB VisualBasic Parser Scanner Lexer Emit CodeGeneration Metadata IL Compilation Scripting Syntax Semantics</PackageTags> <ThirdPartyNoticesFilePath>$(MSBuildThisFileDirectory)..\..\src\NuGet\ThirdPartyNotices.rtf</ThirdPartyNoticesFilePath> <VSSDKTargetPlatformRegRootSuffix>RoslynDev</VSSDKTargetPlatformRegRootSuffix> <CommonExtensionInstallationRoot>CommonExtensions</CommonExtensionInstallationRoot> <LanguageServicesExtensionInstallationFolder>Microsoft\ManagedLanguages\VBCSharp\LanguageServices</LanguageServicesExtensionInstallationFolder> <RestoreUseStaticGraphEvaluation>true</RestoreUseStaticGraphEvaluation> <!-- Disable the implicit nuget fallback folder as it makes it hard to locate and copy ref assemblies to the test output folder --> <DisableImplicitNuGetFallbackFolder>true</DisableImplicitNuGetFallbackFolder> <ToolsetPackagesDir>$(RepoRoot)build\ToolsetPackages\</ToolsetPackagesDir> <UseSharedCompilation>true</UseSharedCompilation> <Features>strict</Features> <ProduceReferenceAssembly>true</ProduceReferenceAssembly> <GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateFullPaths>true</GenerateFullPaths> <!-- Set to non-existent file to prevent common targets from importing Microsoft.CodeAnalysis.targets --> <CodeAnalysisTargets>NON_EXISTENT_FILE</CodeAnalysisTargets> <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">15.0</VisualStudioVersion> <VisualStudioReferenceMajorVersion Condition="'$(VisualStudioReferenceMajorVersion)' == ''">$(VisualStudioVersion.Substring($([System.Convert]::ToInt32(0)), $(VisualStudioVersion.IndexOf('.'))))</VisualStudioReferenceMajorVersion> <VisualStudioReferenceAssemblyVersion Condition="'$(VisualStudioReferenceAssemblyVersion)' == ''">$(VisualStudioReferenceMajorVersion).0.0.0</VisualStudioReferenceAssemblyVersion> <MinimumVisualStudioVersion>$(VisualStudioVersion)</MinimumVisualStudioVersion> <MinimumMSBuildVersion>15.7.0</MinimumMSBuildVersion> <!-- Disable AppX packaging for the Roslyn source. Not setting this to false has the side effect that any builds of portable projects end up in a sub folder of $(OutputPath). Search for this flag in Microsoft.Common.CurrentVersion.targets to see how it is consumed --> <WindowsAppContainer>false</WindowsAppContainer> <EnableDefaultNoneItems>false</EnableDefaultNoneItems> <Nullable>enable</Nullable> </PropertyGroup> <!-- Disable Source Link and Xliff in WPF temp projects to avoid generating non-deterministic file names to obj dir. The project name is non-deterministic and is included in the Source Link json file name and xlf directory names. It's also not necessary to generate these assets. --> <PropertyGroup Condition="'$(IsWpfTempProject)' == 'true'"> <EnableSourceLink>false</EnableSourceLink> <DeterministicSourcePaths>false</DeterministicSourcePaths> <EnableXlfLocalization>false</EnableXlfLocalization> </PropertyGroup> <PropertyGroup Condition="'$(IsTestProject)' == 'true'" > <!-- Choose default target frameworks to use for testing on Mono and Core. These may be overridden by projects that need to be skipped. --> <TestTargetFrameworks Condition="'$(TestRuntime)' == 'Mono'">net46;net472</TestTargetFrameworks> <TestTargetFrameworks Condition="'$(TestRuntime)' == 'Core'">netcoreapp3.1;net5.0</TestTargetFrameworks> <XUnitDesktopSettingsFile>$(MSBuildThisFileDirectory)..\config\xunit.runner.json</XUnitDesktopSettingsFile> <XUnitCoreSettingsFile>$(MSBuildThisFileDirectory)..\config\xunit.runner.json</XUnitCoreSettingsFile> </PropertyGroup> <!-- Keys used by InternalsVisibleTo attributes. --> <PropertyGroup> <MoqPublicKey>0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7</MoqPublicKey> <VisualStudioKey>002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293</VisualStudioKey> <MonoDevelopKey>002400000c800000940000000602000000240000525341310004000001000100e1290d741888d13312c0cd1f72bb843236573c80158a286f11bb98de5ee8acc3142c9c97b472684e521ae45125d7414558f2e70ac56504f3e8fe80830da2cdb1cda8504e8d196150d05a214609234694ec0ebf4b37fc7537e09d877c3e65000f7467fa3adb6e62c82b10ada1af4a83651556c7d949959817fed97480839dd39b</MonoDevelopKey> <RazorKey>0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb</RazorKey> <AspNetCoreKey>$(RazorKey)</AspNetCoreKey> <IntelliCodeCSharpKey>0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9</IntelliCodeCSharpKey> <IntelliCodeKey>002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293</IntelliCodeKey> <FSharpKey>$(VisualStudioKey)</FSharpKey> <TypeScriptKey>$(VisualStudioKey)</TypeScriptKey> <VisualStudioDebuggerKey>$(VisualStudioKey)</VisualStudioDebuggerKey> <XamarinKey>002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df</XamarinKey> <UnitTestingKey>$(VisualStudioKey)</UnitTestingKey> <OmniSharpKey>0024000004800000940000000602000000240000525341310004000001000100917302efc152e6464679d4625bd9989e12d4662a9eaadf284d04992881c0e7b16e756e63ef200a02c4054d4d31e21b9aa0b0b873bcefca8cd42ec583a3db509665c9b22318ceceec581663fc07e2422bb2135539ba8a517c209ac175fff07c5af10cef636e04cae91d28f51fcde5d14c1a9bfed06e096cf977fd0d60002a3ea6</OmniSharpKey> </PropertyGroup> <!-- Enable hard links for the build. This is not done by default due to fears about inadvertently corrupting the NuGet cache (hard links in the output directory will point into the cache). The build itself will not due this but a developer directly modifying this directory could cause it to happen. Developers who do not modify the output directory directly can enable this safely Related discussion in https://github.com/dotnet/roslyn/issues/30005 --> <PropertyGroup Condition="'$(ROSLYNUSEHARDLINKS)' != ''"> <CreateHardLinksForCopyFilesToOutputDirectoryIfPossible>true</CreateHardLinksForCopyFilesToOutputDirectoryIfPossible> <CreateHardLinksForCopyAdditionalFilesIfPossible>true</CreateHardLinksForCopyAdditionalFilesIfPossible> <CreateHardLinksForCopyLocalIfPossible>true</CreateHardLinksForCopyLocalIfPossible> <CreateHardLinksForPublishFilesIfPossible>true</CreateHardLinksForPublishFilesIfPossible> </PropertyGroup> <!-- Windows specific settings --> <PropertyGroup Condition="'$(OS)' == 'Windows_NT'"> <DeployExtension Condition="'$(VisualStudioVersion)' != '15.0' and '$(VisualStudioVersion)' != '16.0'">false</DeployExtension> </PropertyGroup> <PropertyGroup Condition="'$(DevEnvDir)' == ''"> <DevEnvDir>$([System.Environment]::ExpandEnvironmentVariables("%VS$(VisualStudioReferenceMajorVersion)0COMNTOOLS%"))</DevEnvDir> <DevEnvDir>$(DevEnvDir)\..\IDE</DevEnvDir> <DevEnvDir>$([System.IO.Path]::GetFullPath('$(DevEnvDir)'))</DevEnvDir> </PropertyGroup> <!-- Bootstrapping compilers --> <Import Project="Bootstrap.props" Condition="'$(BootstrapBuildPath)' != ''" /> <!-- Analyzers --> <ItemGroup Condition="'$(DotNetBuildFromSource)' != 'true'"> <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="$(MicrosoftCodeAnalysisNetAnalyzersVersion)" PrivateAssets="all" /> <PackageReference Include="Roslyn.Diagnostics.Analyzers" Version="$(RoslynDiagnosticsAnalyzersVersion)" PrivateAssets="all" /> <PackageReference Include="Microsoft.VisualStudio.Threading.Analyzers" Version="$(MicrosoftVisualStudioThreadingAnalyzersVersion)" PrivateAssets="all" /> <PackageReference Include="Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers" Version="$(MicrosoftCodeAnalysisPerformanceSensitiveAnalyzersVersion)" PrivateAssets="all" /> </ItemGroup> <!-- Disable SDK supplied netanalyzers as we reference them from nugets instead --> <PropertyGroup> <EnableNetAnalyzers>false</EnableNetAnalyzers> </PropertyGroup> <!-- Code indexing targets to help generating LSIF from indexing builds. --> <ItemGroup Condition="'$(DotNetBuildFromSource)' != 'true'"> <PackageReference Include="RichCodeNav.EnvVarDump" Version="$(RichCodeNavEnvVarDumpVersion)" PrivateAssets="all" /> </ItemGroup> <!-- Don't inject PerformanceSensitiveAttribute source by default to avoid duplicate definitions caused by IVT. This needs to be set to true in projects at the root of IVT trees, in order for PerformanceSensitiveAnalyzers to work. --> <PropertyGroup Condition="'$(GeneratePerformanceSensitiveAttribute)' == ''"> <GeneratePerformanceSensitiveAttribute>false</GeneratePerformanceSensitiveAttribute> </PropertyGroup> <!-- Language-specific analyzer packages --> <Choose> <When Condition="'$(Language)' == 'VB'"> <ItemGroup Condition="'$(RoslynCheckCodeStyle)' == 'true'"> <PackageReference Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle" Version="$(MicrosoftCodeAnalysisVisualBasicCodeStyleVersion)" PrivateAssets="all" /> </ItemGroup> </When> <When Condition="'$(Language)' == 'C#'"> <ItemGroup Condition="'$(RoslynCheckCodeStyle)' == 'true'"> <PackageReference Include="Microsoft.CodeAnalysis.CSharp.CodeStyle" Version="$(MicrosoftCodeAnalysisCSharpCodeStyleVersion)" PrivateAssets="all" /> </ItemGroup> </When> </Choose> <PropertyGroup Condition="'$(RoslynEnforceCodeStyle)' != 'true'"> <!-- Don't treat FormattingAnalyzer as an error, even when TreatWarningsAsErrors is specified. --> <WarningsNotAsErrors>$(WarningsNotAsErrors);IDE0055</WarningsNotAsErrors> </PropertyGroup> <!-- Language specific settings --> <Choose> <!-- VB specific settings --> <When Condition="'$(Language)' == 'VB'"> <PropertyGroup> <LangVersion>16</LangVersion> <NoWarn>$(NoWarn);40057</NoWarn> <VBRuntime>Embed</VBRuntime> </PropertyGroup> <ItemGroup> <Import Include="Microsoft.VisualBasic" /> <Import Include="System" /> <Import Include="System.Collections" /> <Import Include="System.Collections.Generic" /> <Import Include="System.Diagnostics" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' != 'net20'"> <Import Include="System.Linq" /> </ItemGroup> <PropertyGroup> <DefineConstants Condition="'$(InitialDefineConstants)' != ''">$(InitialDefineConstants)</DefineConstants> </PropertyGroup> </When> <!-- C# specific settings --> <When Condition="'$(Language)' == 'C#'"> <PropertyGroup> <LangVersion>preview</LangVersion> <WarningLevel>9999</WarningLevel> <ErrorReport>prompt</ErrorReport> <!-- Suppress the following warnings by default for C# projects 1573: Suppressed in order to allow documentation for some but not all parameters. A warning will still be reported if the documentation defines/references a parameter which does not exist. 1591: So far we've chosen to implicitly implement interfaces and as a consequence the methods are public. We don't want to duplicate documentation for them and hence suppress this warning until we get closer to release and a more thorough documentation story --> <NoWarn>$(NoWarn);1573;1591;1701</NoWarn> </PropertyGroup> <PropertyGroup> <DefineConstants Condition="'$(InitialDefineConstants)' != ''">$(DefineConstants);$(InitialDefineConstants)</DefineConstants> </PropertyGroup> </When> </Choose> <PropertyGroup Condition="'$(DotNetBuildFromSource)' == 'true'"> <!-- https://github.com/dotnet/roslyn/issues/38433 Vbc does not like the extra semicolon --> <DefineConstants Condition="'$(DefineConstants)' != ''">DOTNET_BUILD_FROM_SOURCE;$(DefineConstants)</DefineConstants> <DefineConstants Condition="'$(DefineConstants)' == ''">DOTNET_BUILD_FROM_SOURCE</DefineConstants> </PropertyGroup> </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> <PropertyGroup> <Copyright>$(CopyrightMicrosoft)</Copyright> <PackageLicenseExpression>MIT</PackageLicenseExpression> <PackageTags>Roslyn CodeAnalysis Compiler CSharp VB VisualBasic Parser Scanner Lexer Emit CodeGeneration Metadata IL Compilation Scripting Syntax Semantics</PackageTags> <ThirdPartyNoticesFilePath>$(MSBuildThisFileDirectory)..\..\src\NuGet\ThirdPartyNotices.rtf</ThirdPartyNoticesFilePath> <VSSDKTargetPlatformRegRootSuffix>RoslynDev</VSSDKTargetPlatformRegRootSuffix> <CommonExtensionInstallationRoot>CommonExtensions</CommonExtensionInstallationRoot> <LanguageServicesExtensionInstallationFolder>Microsoft\ManagedLanguages\VBCSharp\LanguageServices</LanguageServicesExtensionInstallationFolder> <RestoreUseStaticGraphEvaluation>true</RestoreUseStaticGraphEvaluation> <!-- Disable the implicit nuget fallback folder as it makes it hard to locate and copy ref assemblies to the test output folder --> <DisableImplicitNuGetFallbackFolder>true</DisableImplicitNuGetFallbackFolder> <ToolsetPackagesDir>$(RepoRoot)build\ToolsetPackages\</ToolsetPackagesDir> <UseSharedCompilation>true</UseSharedCompilation> <Features>strict</Features> <ProduceReferenceAssembly>true</ProduceReferenceAssembly> <GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateFullPaths>true</GenerateFullPaths> <!-- Set to non-existent file to prevent common targets from importing Microsoft.CodeAnalysis.targets --> <CodeAnalysisTargets>NON_EXISTENT_FILE</CodeAnalysisTargets> <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">15.0</VisualStudioVersion> <VisualStudioReferenceMajorVersion Condition="'$(VisualStudioReferenceMajorVersion)' == ''">$(VisualStudioVersion.Substring($([System.Convert]::ToInt32(0)), $(VisualStudioVersion.IndexOf('.'))))</VisualStudioReferenceMajorVersion> <VisualStudioReferenceAssemblyVersion Condition="'$(VisualStudioReferenceAssemblyVersion)' == ''">$(VisualStudioReferenceMajorVersion).0.0.0</VisualStudioReferenceAssemblyVersion> <MinimumVisualStudioVersion>$(VisualStudioVersion)</MinimumVisualStudioVersion> <MinimumMSBuildVersion>15.7.0</MinimumMSBuildVersion> <!-- Disable AppX packaging for the Roslyn source. Not setting this to false has the side effect that any builds of portable projects end up in a sub folder of $(OutputPath). Search for this flag in Microsoft.Common.CurrentVersion.targets to see how it is consumed --> <WindowsAppContainer>false</WindowsAppContainer> <EnableDefaultNoneItems>false</EnableDefaultNoneItems> <Nullable>enable</Nullable> </PropertyGroup> <!-- Disable Source Link and Xliff in WPF temp projects to avoid generating non-deterministic file names to obj dir. The project name is non-deterministic and is included in the Source Link json file name and xlf directory names. It's also not necessary to generate these assets. --> <PropertyGroup Condition="'$(IsWpfTempProject)' == 'true'"> <EnableSourceLink>false</EnableSourceLink> <DeterministicSourcePaths>false</DeterministicSourcePaths> <EnableXlfLocalization>false</EnableXlfLocalization> </PropertyGroup> <PropertyGroup Condition="'$(IsTestProject)' == 'true'" > <!-- Choose default target frameworks to use for testing on Mono and Core. These may be overridden by projects that need to be skipped. --> <TestTargetFrameworks Condition="'$(TestRuntime)' == 'Mono'">net46;net472</TestTargetFrameworks> <TestTargetFrameworks Condition="'$(TestRuntime)' == 'Core'">netcoreapp3.1;net5.0</TestTargetFrameworks> <XUnitDesktopSettingsFile>$(MSBuildThisFileDirectory)..\config\xunit.runner.json</XUnitDesktopSettingsFile> <XUnitCoreSettingsFile>$(MSBuildThisFileDirectory)..\config\xunit.runner.json</XUnitCoreSettingsFile> </PropertyGroup> <!-- Keys used by InternalsVisibleTo attributes. --> <PropertyGroup> <MoqPublicKey>0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7</MoqPublicKey> <VisualStudioKey>002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293</VisualStudioKey> <MonoDevelopKey>002400000c800000940000000602000000240000525341310004000001000100e1290d741888d13312c0cd1f72bb843236573c80158a286f11bb98de5ee8acc3142c9c97b472684e521ae45125d7414558f2e70ac56504f3e8fe80830da2cdb1cda8504e8d196150d05a214609234694ec0ebf4b37fc7537e09d877c3e65000f7467fa3adb6e62c82b10ada1af4a83651556c7d949959817fed97480839dd39b</MonoDevelopKey> <RazorKey>0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb</RazorKey> <AspNetCoreKey>$(RazorKey)</AspNetCoreKey> <IntelliCodeCSharpKey>0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9</IntelliCodeCSharpKey> <IntelliCodeKey>002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293</IntelliCodeKey> <FSharpKey>$(VisualStudioKey)</FSharpKey> <TypeScriptKey>$(VisualStudioKey)</TypeScriptKey> <VisualStudioDebuggerKey>$(VisualStudioKey)</VisualStudioDebuggerKey> <XamarinKey>002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df</XamarinKey> <UnitTestingKey>$(VisualStudioKey)</UnitTestingKey> <OmniSharpKey>0024000004800000940000000602000000240000525341310004000001000100917302efc152e6464679d4625bd9989e12d4662a9eaadf284d04992881c0e7b16e756e63ef200a02c4054d4d31e21b9aa0b0b873bcefca8cd42ec583a3db509665c9b22318ceceec581663fc07e2422bb2135539ba8a517c209ac175fff07c5af10cef636e04cae91d28f51fcde5d14c1a9bfed06e096cf977fd0d60002a3ea6</OmniSharpKey> </PropertyGroup> <!-- Enable hard links for the build. This is not done by default due to fears about inadvertently corrupting the NuGet cache (hard links in the output directory will point into the cache). The build itself will not due this but a developer directly modifying this directory could cause it to happen. Developers who do not modify the output directory directly can enable this safely Related discussion in https://github.com/dotnet/roslyn/issues/30005 --> <PropertyGroup Condition="'$(ROSLYNUSEHARDLINKS)' != ''"> <CreateHardLinksForCopyFilesToOutputDirectoryIfPossible>true</CreateHardLinksForCopyFilesToOutputDirectoryIfPossible> <CreateHardLinksForCopyAdditionalFilesIfPossible>true</CreateHardLinksForCopyAdditionalFilesIfPossible> <CreateHardLinksForCopyLocalIfPossible>true</CreateHardLinksForCopyLocalIfPossible> <CreateHardLinksForPublishFilesIfPossible>true</CreateHardLinksForPublishFilesIfPossible> </PropertyGroup> <!-- Windows specific settings --> <PropertyGroup Condition="'$(OS)' == 'Windows_NT'"> <DeployExtension Condition="'$(VisualStudioVersion)' != '15.0' and '$(VisualStudioVersion)' != '16.0'">false</DeployExtension> </PropertyGroup> <PropertyGroup Condition="'$(DevEnvDir)' == ''"> <DevEnvDir>$([System.Environment]::ExpandEnvironmentVariables("%VS$(VisualStudioReferenceMajorVersion)0COMNTOOLS%"))</DevEnvDir> <DevEnvDir>$(DevEnvDir)\..\IDE</DevEnvDir> <DevEnvDir>$([System.IO.Path]::GetFullPath('$(DevEnvDir)'))</DevEnvDir> </PropertyGroup> <!-- Bootstrapping compilers --> <Import Project="Bootstrap.props" Condition="'$(BootstrapBuildPath)' != ''" /> <!-- Analyzers --> <ItemGroup Condition="'$(DotNetBuildFromSource)' != 'true'"> <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="$(MicrosoftCodeAnalysisNetAnalyzersVersion)" PrivateAssets="all" /> <PackageReference Include="Roslyn.Diagnostics.Analyzers" Version="$(RoslynDiagnosticsAnalyzersVersion)" PrivateAssets="all" /> <PackageReference Include="Microsoft.VisualStudio.Threading.Analyzers" Version="$(MicrosoftVisualStudioThreadingAnalyzersVersion)" PrivateAssets="all" /> <PackageReference Include="Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers" Version="$(MicrosoftCodeAnalysisPerformanceSensitiveAnalyzersVersion)" PrivateAssets="all" /> </ItemGroup> <!-- Disable SDK supplied netanalyzers as we reference them from nugets instead --> <PropertyGroup> <EnableNetAnalyzers>false</EnableNetAnalyzers> </PropertyGroup> <!-- Code indexing targets to help generating LSIF from indexing builds. --> <ItemGroup Condition="'$(DotNetBuildFromSource)' != 'true'"> <PackageReference Include="RichCodeNav.EnvVarDump" Version="$(RichCodeNavEnvVarDumpVersion)" PrivateAssets="all" /> </ItemGroup> <!-- Don't inject PerformanceSensitiveAttribute source by default to avoid duplicate definitions caused by IVT. This needs to be set to true in projects at the root of IVT trees, in order for PerformanceSensitiveAnalyzers to work. --> <PropertyGroup Condition="'$(GeneratePerformanceSensitiveAttribute)' == ''"> <GeneratePerformanceSensitiveAttribute>false</GeneratePerformanceSensitiveAttribute> </PropertyGroup> <!-- Language-specific analyzer packages --> <Choose> <When Condition="'$(Language)' == 'VB'"> <ItemGroup Condition="'$(RoslynCheckCodeStyle)' == 'true'"> <PackageReference Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle" Version="$(MicrosoftCodeAnalysisVisualBasicCodeStyleVersion)" PrivateAssets="all" /> </ItemGroup> </When> <When Condition="'$(Language)' == 'C#'"> <ItemGroup Condition="'$(RoslynCheckCodeStyle)' == 'true'"> <PackageReference Include="Microsoft.CodeAnalysis.CSharp.CodeStyle" Version="$(MicrosoftCodeAnalysisCSharpCodeStyleVersion)" PrivateAssets="all" /> </ItemGroup> </When> </Choose> <PropertyGroup Condition="'$(RoslynEnforceCodeStyle)' != 'true'"> <!-- Don't treat FormattingAnalyzer as an error, even when TreatWarningsAsErrors is specified. --> <WarningsNotAsErrors>$(WarningsNotAsErrors);IDE0055</WarningsNotAsErrors> </PropertyGroup> <!-- Language specific settings --> <Choose> <!-- VB specific settings --> <When Condition="'$(Language)' == 'VB'"> <PropertyGroup> <LangVersion>16</LangVersion> <NoWarn>$(NoWarn);40057</NoWarn> <VBRuntime>Embed</VBRuntime> </PropertyGroup> <ItemGroup> <Import Include="Microsoft.VisualBasic" /> <Import Include="System" /> <Import Include="System.Collections" /> <Import Include="System.Collections.Generic" /> <Import Include="System.Diagnostics" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' != 'net20'"> <Import Include="System.Linq" /> </ItemGroup> <PropertyGroup> <DefineConstants Condition="'$(InitialDefineConstants)' != ''">$(InitialDefineConstants)</DefineConstants> </PropertyGroup> </When> <!-- C# specific settings --> <When Condition="'$(Language)' == 'C#'"> <PropertyGroup> <LangVersion>preview</LangVersion> <WarningLevel>9999</WarningLevel> <ErrorReport>prompt</ErrorReport> <!-- Suppress the following warnings by default for C# projects 1573: Suppressed in order to allow documentation for some but not all parameters. A warning will still be reported if the documentation defines/references a parameter which does not exist. 1591: So far we've chosen to implicitly implement interfaces and as a consequence the methods are public. We don't want to duplicate documentation for them and hence suppress this warning until we get closer to release and a more thorough documentation story --> <NoWarn>$(NoWarn);1573;1591;1701</NoWarn> </PropertyGroup> <PropertyGroup> <DefineConstants Condition="'$(InitialDefineConstants)' != ''">$(DefineConstants);$(InitialDefineConstants)</DefineConstants> </PropertyGroup> </When> </Choose> <PropertyGroup Condition="'$(DotNetBuildFromSource)' == 'true'"> <!-- https://github.com/dotnet/roslyn/issues/38433 Vbc does not like the extra semicolon --> <DefineConstants Condition="'$(DefineConstants)' != ''">DOTNET_BUILD_FROM_SOURCE;$(DefineConstants)</DefineConstants> <DefineConstants Condition="'$(DefineConstants)' == ''">DOTNET_BUILD_FROM_SOURCE</DefineConstants> </PropertyGroup> </Project>
1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/EditorFeatures/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api; using Microsoft.CodeAnalysis.ExternalAccess.Watch.Api; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public sealed partial class EditAndContinueWorkspaceServiceTests : TestBase { private static readonly TestComposition s_composition = FeaturesTestCompositions.Features; private static readonly ActiveStatementSpanProvider s_noActiveSpans = (_, _, _) => new(ImmutableArray<ActiveStatementSpan>.Empty); private const TargetFramework DefaultTargetFramework = TargetFramework.NetStandard20; private Func<Project, CompilationOutputs> _mockCompilationOutputsProvider; private readonly List<string> _telemetryLog; private int _telemetryId; private readonly MockManagedEditAndContinueDebuggerService _debuggerService; public EditAndContinueWorkspaceServiceTests() { _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()); _telemetryLog = new List<string>(); _debuggerService = new MockManagedEditAndContinueDebuggerService() { LoadedModules = new Dictionary<Guid, ManagedEditAndContinueAvailability>() }; } private TestWorkspace CreateWorkspace(out Solution solution, out EditAndContinueWorkspaceService service, Type[] additionalParts = null) { var workspace = new TestWorkspace(composition: s_composition.AddParts(additionalParts)); solution = workspace.CurrentSolution; service = GetEditAndContinueService(workspace); return workspace; } private static SourceText GetAnalyzerConfigText((string key, string value)[] analyzerConfig) => SourceText.From("[*.*]" + Environment.NewLine + string.Join(Environment.NewLine, analyzerConfig.Select(c => $"{c.key} = {c.value}"))); private static (Solution, Document) AddDefaultTestProject( Solution solution, string source, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { solution = AddDefaultTestProject(solution, new[] { source }, generator, additionalFileText, analyzerConfig); return (solution, solution.Projects.Single().Documents.Single()); } private static Solution AddDefaultTestProject( Solution solution, string[] sources, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { var project = solution. AddProject("proj", "proj", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = project.Solution; if (generator != null) { solution = solution.AddAnalyzerReference(project.Id, new TestGeneratorReference(generator)); } if (additionalFileText != null) { solution = solution.AddAdditionalDocument(DocumentId.CreateNewId(project.Id), "additional", SourceText.From(additionalFileText)); } if (analyzerConfig != null) { solution = solution.AddAnalyzerConfigDocument( DocumentId.CreateNewId(project.Id), name: "config", GetAnalyzerConfigText(analyzerConfig), filePath: Path.Combine(TempRoot.Root, "config")); } Document document = null; var i = 1; foreach (var source in sources) { var fileName = $"test{i++}.cs"; document = solution.GetProject(project.Id). AddDocument(fileName, SourceText.From(source, Encoding.UTF8), filePath: Path.Combine(TempRoot.Root, fileName)); solution = document.Project.Solution; } return document.Project.Solution; } private EditAndContinueWorkspaceService GetEditAndContinueService(Workspace workspace) { var service = (EditAndContinueWorkspaceService)workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); var accessor = service.GetTestAccessor(); accessor.SetOutputProvider(project => _mockCompilationOutputsProvider(project)); return service; } private async Task<DebuggingSession> StartDebuggingSessionAsync( EditAndContinueWorkspaceService service, Solution solution, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var sessionId = await service.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var session = service.GetTestAccessor().GetDebuggingSession(sessionId); if (initialState != CommittedSolution.DocumentState.None) { SetDocumentsState(session, solution, initialState); } session.GetTestAccessor().SetTelemetryLogger((id, message) => _telemetryLog.Add($"{id}: {message.GetMessage()}"), () => ++_telemetryId); return session; } private void EnterBreakState( DebuggingSession session, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements = default, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { _debuggerService.GetActiveStatementsImpl = () => activeStatements.NullToEmpty(); session.BreakStateEntered(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private void ExitBreakState() { _debuggerService.GetActiveStatementsImpl = () => ImmutableArray<ManagedActiveStatementDebugInfo>.Empty; } private static void CommitSolutionUpdate(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.CommitSolutionUpdate(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static void EndDebuggingSession(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.EndSession(out var documentsToReanalyze, out _); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static async Task<(ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics)> EmitSolutionUpdateAsync( DebuggingSession session, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider = null) { var result = await session.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider ?? s_noActiveSpans, CancellationToken.None); return (result.ModuleUpdates, result.GetDiagnosticData(solution)); } internal static void SetDocumentsState(DebuggingSession session, Solution solution, CommittedSolution.DocumentState state) { foreach (var project in solution.Projects) { foreach (var document in project.Documents) { session.LastCommittedSolution.Test_SetDocumentState(document.Id, state); } } } private static IEnumerable<string> InspectDiagnostics(ImmutableArray<DiagnosticData> actual) => actual.Select(d => $"{d.ProjectId} {InspectDiagnostic(d)}"); private static string InspectDiagnostic(DiagnosticData diagnostic) => $"{diagnostic.Severity} {diagnostic.Id}: {diagnostic.Message}"; internal static Guid ReadModuleVersionId(Stream stream) { using var peReader = new PEReader(stream); var metadataReader = peReader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; return metadataReader.GetGuid(mvidHandle); } private Guid EmitAndLoadLibraryToDebuggee(string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "") { var moduleId = EmitLibrary(source, sourceFilePath, encoding, assemblyName); LoadLibraryToDebuggee(moduleId); return moduleId; } private void LoadLibraryToDebuggee(Guid moduleId, ManagedEditAndContinueAvailability availability = default) { _debuggerService.LoadedModules.Add(moduleId, availability); } private Guid EmitLibrary( string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { return EmitLibrary(new[] { (source, sourceFilePath ?? Path.Combine(TempRoot.Root, "test1.cs")) }, encoding, assemblyName, pdbFormat, generator, additionalFileText, analyzerOptions); } private Guid EmitLibrary( (string content, string filePath)[] sources, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { encoding ??= Encoding.UTF8; var parseOptions = TestOptions.RegularPreview; var trees = sources.Select(source => { var sourceText = SourceText.From(new MemoryStream(encoding.GetBytes(source.content)), encoding, checksumAlgorithm: SourceHashAlgorithm.Sha256); return SyntaxFactory.ParseSyntaxTree(sourceText, parseOptions, source.filePath); }); Compilation compilation = CSharpTestBase.CreateCompilation(trees.ToArray(), options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: assemblyName); if (generator != null) { var optionsProvider = (analyzerOptions != null) ? new EditAndContinueTestAnalyzerConfigOptionsProvider(analyzerOptions) : null; var additionalTexts = (additionalFileText != null) ? new[] { new InMemoryAdditionalText("additional_file", additionalFileText) } : null; var generatorDriver = CSharpGeneratorDriver.Create(new[] { generator }, additionalTexts, parseOptions, optionsProvider); generatorDriver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); generatorDiagnostics.Verify(); compilation = outputCompilation; } return EmitLibrary(compilation, pdbFormat); } private Guid EmitLibrary(Compilation compilation, DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb) { var (peImage, pdbImage) = compilation.EmitToArrays(new EmitOptions(debugInformationFormat: pdbFormat)); var symReader = SymReaderTestHelpers.OpenDummySymReader(pdbImage); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleId = moduleMetadata.GetModuleVersionId(); // associate the binaries with the project (assumes a single project) _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenAssemblyStreamImpl = () => { var stream = new MemoryStream(); peImage.WriteToStream(stream); stream.Position = 0; return stream; }, OpenPdbStreamImpl = () => { var stream = new MemoryStream(); pdbImage.WriteToStream(stream); stream.Position = 0; return stream; } }; return moduleId; } private static SourceText CreateSourceTextFromFile(string path) { using var stream = File.OpenRead(path); return SourceText.From(stream, Encoding.UTF8, SourceHashAlgorithm.Sha256); } private static TextSpan GetSpan(string str, string substr) => new TextSpan(str.IndexOf(substr), substr.Length); private static void VerifyReadersDisposed(IEnumerable<IDisposable> readers) { foreach (var reader in readers) { Assert.Throws<ObjectDisposedException>(() => { if (reader is MetadataReaderProvider md) { md.GetMetadataReader(); } else { ((DebugInformationReaderProvider)reader).CreateEditAndContinueMethodDebugInfoReader(); } }); } } private static DocumentInfo CreateDesignTimeOnlyDocument(ProjectId projectId, string name = "design-time-only.cs", string path = "design-time-only.cs") => DocumentInfo.Create( DocumentId.CreateNewId(projectId, name), name: name, folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class DTO {}"), VersionStamp.Create(), path)), filePath: path, isGenerated: false, designTimeOnly: true, documentServiceProvider: null); internal sealed class FailingTextLoader : TextLoader { public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { Assert.True(false, $"Content of document {documentId} should never be loaded"); throw ExceptionUtilities.Unreachable; } } [Theory] [CombinatorialData] public async Task StartDebuggingSession_CapturingDocuments(bool captureAllDocuments) { var encodingA = Encoding.BigEndianUnicode; var encodingB = Encoding.Unicode; var encodingC = Encoding.GetEncoding("SJIS"); var encodingE = Encoding.UTF8; var sourceA1 = "class A {}"; var sourceB1 = "class B { int F() => 1; }"; var sourceB2 = "class B { int F() => 2; }"; var sourceB3 = "class B { int F() => 3; }"; var sourceC1 = "class C { const char L = 'ワ'; }"; var sourceD1 = "dummy code"; var sourceE1 = "class E { }"; var sourceBytesA1 = encodingA.GetBytes(sourceA1); var sourceBytesB1 = encodingB.GetBytes(sourceB1); var sourceBytesC1 = encodingC.GetBytes(sourceC1); var sourceBytesE1 = encodingE.GetBytes(sourceE1); var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllBytes(sourceBytesA1); var sourceFileB = dir.CreateFile("B.cs").WriteAllBytes(sourceBytesB1); var sourceFileC = dir.CreateFile("C.cs").WriteAllBytes(sourceBytesC1); var sourceFileD = dir.CreateFile("dummy").WriteAllText(sourceD1); var sourceFileE = dir.CreateFile("E.cs").WriteAllBytes(sourceBytesE1); var sourceTreeA1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesA1, sourceBytesA1.Length, encodingA, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileA.Path); var sourceTreeB1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesB1, sourceBytesB1.Length, encodingB, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileB.Path); var sourceTreeC1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesC1, sourceBytesC1.Length, encodingC, SourceHashAlgorithm.Sha1), TestOptions.Regular, sourceFileC.Path); // E is not included in the compilation: var compilation = CSharpTestBase.CreateCompilation(new[] { sourceTreeA1, sourceTreeB1, sourceTreeC1 }, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "P"); EmitLibrary(compilation); // change content of B on disk: sourceFileB.WriteAllText(sourceB2, encodingB); // prepare workspace as if it was loaded from project files: using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var projectP = solution.AddProject("P", "P", LanguageNames.CSharp); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, encodingA), filePath: sourceFileA.Path)); var documentIdB = DocumentId.CreateNewId(projectP.Id, debugName: "B"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdB, name: "B", loader: new FileTextLoader(sourceFileB.Path, encodingB), filePath: sourceFileB.Path)); var documentIdC = DocumentId.CreateNewId(projectP.Id, debugName: "C"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdC, name: "C", loader: new FileTextLoader(sourceFileC.Path, encodingC), filePath: sourceFileC.Path)); var documentIdE = DocumentId.CreateNewId(projectP.Id, debugName: "E"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdE, name: "E", loader: new FileTextLoader(sourceFileE.Path, encodingE), filePath: sourceFileE.Path)); // check that are testing documents whose hash algorithm does not match the PDB (but the hash itself does): Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdA).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdB).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdC).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdE).GetTextSynchronously(default).ChecksumAlgorithm); // design-time-only document with and without absolute path: solution = solution. AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt1.cs", path: Path.Combine(dir.Path, "dt1.cs"))). AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt2.cs", path: "dt2.cs")); // project that does not support EnC - the contents of documents in this project shouldn't be loaded: var projectQ = solution.AddProject("Q", "Q", DummyLanguageService.LanguageName); solution = projectQ.Solution; solution = solution.AddDocument(DocumentInfo.Create( id: DocumentId.CreateNewId(projectQ.Id, debugName: "D"), name: "D", loader: new FailingTextLoader(), filePath: sourceFileD.Path)); var captureMatchingDocuments = captureAllDocuments ? ImmutableArray<DocumentId>.Empty : (from project in solution.Projects from documentId in project.DocumentIds select documentId).ToImmutableArray(); var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments, captureAllDocuments, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = debuggingSession.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)", "(C, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // change content of B on disk again: sourceFileB.WriteAllText(sourceB3, encodingB); solution = solution.WithDocumentTextLoader(documentIdB, new FileTextLoader(sourceFileB.Path, encodingB), PreservationMode.PreserveValue); EnterBreakState(debuggingSession); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{projectP.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFileB.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); } [Fact] public async Task RunMode_ProjectThatDoesNotSupportEnC() { using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; await StartDebuggingSessionAsync(service, solution); // no changes: var document1 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("dummy2")); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task RunMode_DesignTimeOnlyDocument() { var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); var documentInfo = CreateDesignTimeOnlyDocument(document1.Project.Id); solution = solution.WithProjectOutputFilePath(document1.Project.Id, moduleFile.Path).AddDocument(documentInfo); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update a design-time-only source file: solution = solution.WithDocumentText(documentInfo.Id, SourceText.From("class UpdatedC2 {}")); var document2 = solution.GetDocument(documentInfo.Id); // no updates: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // validate solution update status and emit - changes made in design-time-only documents are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0" }, _telemetryLog); } [Fact] public async Task RunMode_ProjectNotBuilt() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.Empty); await StartDebuggingSessionAsync(service, solution); // no changes: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task RunMode_DifferentDocumentWithSameContent() { var source = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source); solution = solution.WithProjectOutputFilePath(document.Project.Id, moduleFile.Path); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update the document var document1 = solution.GetDocument(document.Id); solution = solution.WithDocumentText(document.Id, SourceText.From(source)); var document2 = solution.GetDocument(document.Id); Assert.Equal(document1.Id, document2.Id); Assert.NotSame(document1, document2); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); // validate solution update status and emit - changes made during run mode are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0" }, _telemetryLog); } [Fact] public async Task BreakMode_ProjectThatDoesNotSupportEnC() { using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("dummy2")); var document2 = solution.GetDocument(document1.Id); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); } [Fact] public async Task BreakMode_DesignTimeOnlyDocument_Dynamic() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C {}"); var documentInfo = DocumentInfo.Create( DocumentId.CreateNewId(document.Project.Id), name: "design-time-only.cs", folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class D {}"), VersionStamp.Create(), "design-time-only.cs")), filePath: "design-time-only.cs", isGenerated: false, designTimeOnly: true, documentServiceProvider: null); solution = solution.AddDocument(documentInfo); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.GetDocument(documentInfo.Id); solution = solution.WithDocumentText(document1.Id, SourceText.From("class E {}")); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_DesignTimeOnlyDocument_Wpf(bool delayLoad) { var sourceA = "class A { public void M() { } }"; var sourceB = "class B { public void M() { } }"; var sourceC = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("a.cs").WriteAllText(sourceA); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); var documentB = documentA.Project. AddDocument("b.g.i.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: "b.g.i.cs"); var documentC = documentB.Project. AddDocument("c.g.i.vb", SourceText.From(sourceC, Encoding.UTF8), filePath: "c.g.i.vb"); solution = documentC.Project.Solution; // only compile A; B and C are design-time-only: var moduleId = EmitLibrary(sourceA, sourceFilePath: sourceFileA.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); EnterBreakState(debuggingSession); // change the source (rude edit): solution = solution.WithDocumentText(documentB.Id, SourceText.From("class B { public void RenamedMethod() { } }")); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { public void RenamedMethod() { } }")); var documentB2 = solution.GetDocument(documentB.Id); var documentC2 = solution.GetDocument(documentC.Id); // no Rude Edits reported: Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentB2, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentC2, s_noActiveSpans, CancellationToken.None)); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); if (delayLoad) { LoadLibraryToDebuggee(moduleId); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); } EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task ErrorReadingModuleFile(bool breakMode) { // module file is empty, which will cause a read error: var moduleFile = Temp.CreateFile(); string expectedErrorMessage = null; try { using var stream = File.OpenRead(moduleFile.Path); using var peReader = new PEReader(stream); _ = peReader.GetMetadataReader(); } catch (Exception e) { expectedErrorMessage = e.Message; } using var _w = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, moduleFile.Path, expectedErrorMessage)}" }, InspectDiagnostics(emitDiagnostics)); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0", }, _telemetryLog); } } [Fact] public async Task BreakMode_ErrorReadingPdbFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenPdbStreamImpl = () => { throw new IOException("Error"); } }; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=1" }, _telemetryLog); } [Fact] public async Task BreakMode_ErrorReadingSourceFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); using var fileLock = File.Open(sourceFile.Path, FileMode.Open, FileAccess.Read, FileShare.None); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // try apply changes: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); fileLock.Dispose(); // try apply changes again: (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.NotEmpty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0" }, _telemetryLog); } [Theory] [CombinatorialData] public async Task FileAdded(bool breakMode) { var sourceA = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceB = "class C2 {}"; var sourceFileA = Temp.CreateFile().WriteAllText(sourceA); var sourceFileB = Temp.CreateFile().WriteAllText(sourceB); using var _ = CreateWorkspace(out var solution, out var service); var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); solution = documentA.Project.Solution; // Source B will be added while debugging. EmitAndLoadLibraryToDebuggee(sourceA, sourceFilePath: sourceFileA.Path); var project = documentA.Project; var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // add a source file: var documentB = project.AddDocument("file2.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: sourceFileB.Path); solution = documentB.Project.Solution; documentB = solution.GetDocument(documentB.Id); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(documentB, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0" }, _telemetryLog); } } [Fact] public async Task BreakMode_ModuleDisallowsEditAndContinue() { var moduleId = Guid.NewGuid(); var source1 = @" class C1 { void M() { System.Console.WriteLine(1); System.Console.WriteLine(2); System.Console.WriteLine(3); } }"; var source2 = @" class C1 { void M() { System.Console.WriteLine(9); System.Console.WriteLine(); System.Console.WriteLine(30); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); LoadLibraryToDebuggee(moduleId, new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForRuntime, "*message*")); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // We do not report module diagnostics until emit. // This is to make the analysis deterministic (not dependent on the current state of the debuggee). var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC2016: {string.Format(FeaturesResources.EditAndContinueDisallowedByProject, document2.Project.Name, "*message*")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC2016" }, _telemetryLog); } [Fact] public async Task BreakMode_Encodings() { var source1 = "class C1 { void M() { System.Console.WriteLine(\"ã\"); } }"; var encoding = Encoding.GetEncoding(1252); var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1, encoding); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, encoding), filePath: sourceFile.Path); var documentId = document1.Id; var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path, encoding: encoding); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // Emulate opening the file, which will trigger "out-of-sync" check. // Since we find content matching the PDB checksum we update the committed solution with this source text. // If we used wrong encoding this would lead to a false change detected below. var currentDocument = solution.GetDocument(documentId); await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); // EnC service queries for a document, which triggers read of the source file from disk. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task RudeEdits(bool breakMode) { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0", }, _telemetryLog); } } [Fact] public async Task BreakMode_RudeEdits_SourceGenerators() { var sourceV1 = @" /* GENERATE: class G { int X1 => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X2 => 1; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1, generator: generator); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var generatedDocument = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync()).Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(generatedDocument, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.property_) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(generatedDocument.Id)); } [Theory] [CombinatorialData] public async Task RudeEdits_DocumentOutOfSync(bool breakMode) { var source0 = "class C1 { void M() { System.Console.WriteLine(0); } }"; var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void RenamedMethod() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs"); using var _ = CreateWorkspace(out var solution, out var service); var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; // compile with source0: var moduleId = EmitAndLoadLibraryToDebuggee(source0, sourceFilePath: sourceFile.Path); // update the file with source1 before session starts: sourceFile.WriteAllText(source1); // source1 is reflected in workspace before session starts: var document1 = project.AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); solution = document1.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // no Rude Edits, since the document is out-of-sync var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // update the file to match the build: sourceFile.WriteAllText(source0); // we do not reload the content of out-of-sync file for analyzer query: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // debugger query will trigger reload of out-of-sync file content: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // now we see the rude edit: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0", }, _telemetryLog); } } [Fact] public async Task BreakMode_RudeEdits_DocumentWithoutSequencePoints() { var source1 = "abstract class C { public abstract void M(); }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit since the base document content matches the PDB checksum, so the document is not out-of-sync): solution = solution.WithDocumentText(document1.Id, SourceText.From("abstract class C { public abstract void M(); public abstract void N(); }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0023: " + string.Format(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task BreakMode_RudeEdits_DelayLoadedModule() { var source1 = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit) before the library is loaded: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C { public void Renamed() { } }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // load library to the debuggee: LoadLibraryToDebuggee(moduleId); // Rude Edits still reported: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task BreakMode_SyntaxError() { var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { ")); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=True|HadRudeEdits=False|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0" }, _telemetryLog); } [Fact] public async Task BreakMode_SemanticError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { int i = 0L; System.Console.WriteLine(i); } }", Encoding.UTF8)); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // The EnC analyzer does not check for and block on all semantic errors as they are already reported by diagnostic analyzer. // Blocking update on semantic errors would be possible, but the status check is only an optimization to avoid emitting. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); // TODO: https://github.com/dotnet/roslyn/issues/36061 // Semantic errors should not be reported in emit diagnostics. AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS0266: {string.Format(CSharpResources.ERR_NoImplicitConvCast, "long", "int")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS0266" }, _telemetryLog); } [Fact] public async Task BreakMode_FileStatus_CompilationError() { using var _ = CreateWorkspace(out var solution, out var service); solution = solution. AddProject("A", "A", "C#"). AddDocument("A.cs", "class Program { void Main() { System.Console.WriteLine(1); } }", filePath: "A.cs").Project.Solution. AddProject("B", "B", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("B.cs", "class B {}", filePath: "B.cs").Project.Solution. AddProject("C", "C", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("C.cs", "class C {}", filePath: "C.cs").Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change C.cs to have a compilation error: var projectC = solution.GetProjectsByName("C").Single(); var documentC = projectC.Documents.Single(d => d.Name == "C.cs"); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { void M() { ")); // Common.cs is included in projects B and C. Both of these projects must have no errors, otherwise update is blocked. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "Common.cs", CancellationToken.None)); // No changes in project containing file B.cs. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "B.cs", CancellationToken.None)); // All projects must have no errors. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_EmitError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit but passing no encoding to emulate emit error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", encoding: null)); var document2 = solution.Projects.Single().Documents.Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS8055: {string.Format(CSharpResources.ERR_EncodinglessSyntaxTree)}" }, InspectDiagnostics(emitDiagnostics)); // no emitted delta: Assert.Empty(updates.Updates); // no pending update: Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); Assert.Throws<InvalidOperationException>(() => debuggingSession.CommitSolutionUpdate(out var _)); Assert.Throws<InvalidOperationException>(() => debuggingSession.DiscardSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // solution update status after discarding an update (still has update ready): Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS8055" }, _telemetryLog); } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_ValidSignificantChange_ApplyBeforeFileWatcherEvent(bool saveDocument) { // Scenarios tested: // // SaveDocument=true // workspace: --V0-------------|--V2--------|------------| // file system: --V0---------V1--|-----V2-----|------------| // \--build--/ F5 ^ F10 ^ F10 // save file watcher: no-op // SaveDocument=false // workspace: --V0-------------|--V2--------|----V1------| // file system: --V0---------V1--|------------|------------| // \--build--/ F5 F10 ^ F10 // file watcher: workspace update var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var documentId = document1.Id; solution = document1.Project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // The user opens the source file and changes the source before Roslyn receives file watcher event. var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(documentId); // Save the document: if (saveDocument) { await debuggingSession.OnSourceFileUpdatedAsync(document2); sourceFile.WriteAllText(source2); } // EnC service queries for a document, which triggers read of the source file from disk. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); ExitBreakState(); EnterBreakState(debuggingSession); // file watcher updates the workspace: solution = solution.WithDocumentText(documentId, CreateSourceTextFromFile(sourceFile.Path)); var document3 = solution.Projects.Single().Documents.Single(); var hasChanges = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); if (saveDocument) { Assert.False(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); } else { Assert.True(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); } ExitBreakState(); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_FileUpdateNotObservedBeforeDebuggingSessionStart() { // workspace: --V0--------------V2-------|--------V3------------------V1--------------| // file system: --V0---------V1-----V2-----|------------------------------V1------------| // \--build--/ ^save F5 ^ ^F10 (no change) ^save F10 (ok) // file watcher: no-op // build updates file from V0 -> V1 var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C1 { void M() { System.Console.WriteLine(3); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source2); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document2 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source2, Encoding.UTF8), filePath: sourceFile.Path); var documentId = document2.Id; var project = document2.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // user edits the file: solution = solution.WithDocumentText(documentId, SourceText.From(source3, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); // EnC service queries for a document, but the source file on disk doesn't match the PDB // We don't report rude edits for out-of-sync documents: var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // undo: solution = solution.WithDocumentText(documentId, SourceText.From(source1, Encoding.UTF8)); var currentDocument = solution.GetDocument(documentId); // save (note that this call will fail to match the content with the PDB since it uses the content prior to the actual file write) await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); var (doc, state) = await debuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(documentId, currentDocument, CancellationToken.None); Assert.Null(doc); Assert.Equal(CommittedSolution.DocumentState.OutOfSync, state); sourceFile.WriteAllText(source1); Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); // the content actually hasn't changed: Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_AddedFileNotObservedBeforeDebuggingSessionStart() { // workspace: ------|----V0---------------|---------- // file system: --V0--|---------------------|---------- // F5 ^ ^F10 (no change) // file watcher observes the file var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with no file var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _debuggerService.IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Attach, localizedMessage: "*attached*"); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); // An active statement may be present in the added file since the file exists in the PDB: var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeSpan1 = GetSpan(source1, "System.Console.WriteLine(1);"); var sourceText1 = SourceText.From(source1, Encoding.UTF8); var activeLineSpan1 = sourceText1.Lines.GetLinePositionSpan(activeSpan1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, "test.cs", activeLineSpan1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); // disallow any edits (attach scenario) EnterBreakState(debuggingSession, activeStatements); // File watcher observes the document and adds it to the workspace: var document1 = project.AddDocument("test.cs", sourceText1, filePath: sourceFile.Path); solution = document1.Project.Solution; // We don't report rude edits for the added document: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // TODO: https://github.com/dotnet/roslyn/issues/49938 // We currently create the AS map against the committed solution, which may not contain all documents. // var spans = await service.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); // AssertEx.Equal(new[] { $"({activeLineSpan1}, IsLeafFrame)" }, spans.Single().Select(s => s.ToString())); // No changes. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task BreakMode_ValidSignificantChange_DocumentOutOfSync(bool delayLoad) { var sourceOnDisk = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(sourceOnDisk); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(sourceOnDisk, sourceFilePath: sourceFile.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // no changes have been made to the project Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // a file watcher observed a change and updated the document, so it now reflects the content on disk (the code that we compiled): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceOnDisk, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // the content of the file is now exactly the same as the compiled document, so there is no change to be applied: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); Assert.Empty(debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); } [Theory] [CombinatorialData] public async Task ValidSignificantChange_EmitSuccessful(bool breakMode, bool commitUpdate) { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceV2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); void ValidateDelta(ManagedModuleUpdate delta) { // check emitted delta: Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000001, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); } // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); AssertEx.Equal(updates.Updates, pendingUpdate.Deltas); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); if (commitUpdate) { // all update providers either provided updates or had no change to apply: CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, baselineReaders.Length); Assert.Same(readers[0], baselineReaders[0]); Assert.Same(readers[1], baselineReaders[1]); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: var commitedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.False(commitedUpdateSolutionStatus); } else { // another update provider blocked the update: debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // solution update status after committing an update: var discardedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.True(discardedUpdateSolutionStatus); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); } if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0", }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0", }, _telemetryLog); } } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_ValidSignificantChange_EmitSuccessful_UpdateDeferred(bool commitUpdate) { var dir = Temp.CreateDirectory(); var sourceV1 = "class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilation(sourceV1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "lib"); var (peImage, pdbImage) = compilationV1.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleFile = dir.CreateFile("lib.dll").WriteAllBytes(peImage); var pdbFile = dir.CreateFile("lib.pdb").WriteAllBytes(pdbImage); var moduleId = moduleMetadata.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path, pdbFile.Path); // set up an active statement in the first method, so that we can test preservation of local signature. var activeStatements = ImmutableArray.Create(new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 0), documentName: document1.Name, sourceSpan: new SourceSpan(0, 15, 0, 16), ActiveStatementFlags.IsLeafFrame)); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module is not loaded: EnterBreakState(debuggingSession, activeStatements); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); // delta to apply: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000002, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); if (commitUpdate) { CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); // make another update: EnterBreakState(debuggingSession); // Update M1 - this method has an active statement, so we will attempt to preserve the local signature. // Since the method hasn't been edited before we'll read the baseline PDB to get the signature token. // This validates that the Portable PDB reader can be used (and is not disposed) for a second generation edit. var document3 = solution.GetDocument(document1.Id); solution = solution.WithDocumentText(document3.Id, SourceText.From("class C1 { void M1() { int a = 3; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); } else { debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); } ExitBreakState(); EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task BreakMode_ValidSignificantChange_PartialTypes() { var sourceA1 = @" partial class C { int X = 1; void F() { X = 1; } } partial class D { int U = 1; public D() { } } partial class D { int W = 1; } partial class E { int A; public E(int a) { A = a; } } "; var sourceB1 = @" partial class C { int Y = 1; } partial class E { int B; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; var sourceA2 = @" partial class C { int X = 2; void F() { X = 2; } } partial class D { int U = 2; } partial class D { int W = 2; public D() { } } partial class E { int A = 1; public E(int a) { A = a; } } "; var sourceB2 = @" partial class C { int Y = 2; } partial class E { int B = 2; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { sourceA1, sourceB1 }); var project = solution.Projects.Single(); LoadLibraryToDebuggee(EmitLibrary(new[] { (sourceA1, "test1.cs"), (sourceB1, "test2.cs") })); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): var documentA = project.Documents.First(); var documentB = project.Documents.Skip(1).First(); solution = solution.WithDocumentText(documentA.Id, SourceText.From(sourceA2, Encoding.UTF8)); solution = solution.WithDocumentText(documentB.Id, SourceText.From(sourceB2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(6, delta.UpdatedMethods.Length); // F, C.C(), D.D(), E.E(int), E.E(int, int), lambda AssertEx.SetEqual(new[] { 0x02000002, 0x02000003, 0x02000004, 0x02000005 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } private static EditAndContinueLogEntry Row(int rowNumber, TableIndex table, EditAndContinueOperation operation) => new(MetadataTokens.Handle(table, rowNumber), operation); private static unsafe void VerifyEncLogMetadata(ImmutableArray<byte> delta, params EditAndContinueLogEntry[] expectedRows) { fixed (byte* ptr = delta.ToArray()) { var reader = new MetadataReader(ptr, delta.Length); AssertEx.Equal(expectedRows, reader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString); } static string EncLogRowToString(EditAndContinueLogEntry row) { TableIndex tableIndex; MetadataTokens.TryGetTableIndex(row.Handle.Kind, out tableIndex); return string.Format( "Row({0}, TableIndex.{1}, EditAndContinueOperation.{2})", MetadataTokens.GetRowNumber(row.Handle), tableIndex, row.Operation); } } private static void GenerateSource(GeneratorExecutionContext context) { foreach (var syntaxTree in context.Compilation.SyntaxTrees) { var fileName = PathUtilities.GetFileName(syntaxTree.FilePath); Generate(syntaxTree.GetText().ToString(), fileName); if (context.AnalyzerConfigOptions.GetOptions(syntaxTree).TryGetValue("enc_generator_output", out var optionValue)) { context.AddSource("GeneratedFromOptions_" + fileName, $"class G {{ int X => {optionValue}; }}"); } } foreach (var additionalFile in context.AdditionalFiles) { Generate(additionalFile.GetText()!.ToString(), PathUtilities.GetFileName(additionalFile.Path)); } void Generate(string source, string fileName) { var generatedSource = GetGeneratedCodeFromMarkedSource(source); if (generatedSource != null) { context.AddSource($"Generated_{fileName}", generatedSource); } } } private static string GetGeneratedCodeFromMarkedSource(string markedSource) { const string OpeningMarker = "/* GENERATE:"; const string ClosingMarker = "*/"; var index = markedSource.IndexOf(OpeningMarker); if (index > 0) { index += OpeningMarker.Length; var closing = markedSource.IndexOf(ClosingMarker, index); return markedSource[index..closing].Trim(); } return null; } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate() { var sourceV1 = @" /* GENERATE: class G { int X => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X => 2; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(2, delta.UpdatedMethods.Length); AssertEx.Equal(new[] { 0x02000002, 0x02000003 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate_LineChanges() { var sourceV1 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var sourceV2 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); var lineUpdate = delta.SequencePoints.Single(); AssertEx.Equal(new[] { "3 -> 4" }, lineUpdate.LineUpdates.Select(edit => $"{edit.OldLine} -> {edit.NewLine}")); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentInsert() { var sourceV1 = @" partial class C { int X = 1; } "; var sourceV2 = @" /* GENERATE: partial class C { int Y = 2; } */ partial class C { int X = 1; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); // constructor update Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_AdditionalDocumentUpdate() { var source = @" class C { int Y => 1; } "; var additionalSourceV1 = @" /* GENERATE: class G { int X => 1; } */ "; var additionalSourceV2 = @" /* GENERATE: class G { int X => 2; } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, additionalFileText: additionalSourceV1); var moduleId = EmitLibrary(source, generator: generator, additionalFileText: additionalSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var additionalDocument1 = solution.Projects.Single().AdditionalDocuments.Single(); solution = solution.WithAdditionalDocumentText(additionalDocument1.Id, SourceText.From(additionalSourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_AnalyzerConfigUpdate() { var source = @" class C { int Y => 1; } "; var configV1 = new[] { ("enc_generator_output", "1") }; var configV2 = new[] { ("enc_generator_output", "2") }; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, analyzerConfig: configV1); var moduleId = EmitLibrary(source, generator: generator, analyzerOptions: configV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var configDocument1 = solution.Projects.Single().AnalyzerConfigDocuments.Single(); solution = solution.WithAnalyzerConfigDocumentText(configDocument1.Id, GetAnalyzerConfigText(configV2)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentRemove() { var source1 = ""; var generator = new TestSourceGenerator() { ExecuteImpl = context => context.AddSource("generated", $"class G {{ int X => {context.Compilation.SyntaxTrees.Count()}; }}") }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator); var moduleId = EmitLibrary(source1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // remove the source document (valid edit): solution = document1.Project.Solution.RemoveDocument(document1.Id); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } /// <summary> /// Emulates two updates to Multi-TFM project. /// </summary> [Fact] public async Task TwoUpdatesWithLoadedAndUnloadedModule() { var dir = Temp.CreateDirectory(); var source1 = "class A { void M() { System.Console.WriteLine(1); } }"; var source2 = "class A { void M() { System.Console.WriteLine(2); } }"; var source3 = "class A { void M() { System.Console.WriteLine(3); } }"; var compilationA = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "A"); var compilationB = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "B"); var (peImageA, pdbImageA) = compilationA.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataA = ModuleMetadata.CreateFromImage(peImageA); var moduleFileA = Temp.CreateFile("A.dll").WriteAllBytes(peImageA); var pdbFileA = dir.CreateFile("A.pdb").WriteAllBytes(pdbImageA); var moduleIdA = moduleMetadataA.GetModuleVersionId(); var (peImageB, pdbImageB) = compilationB.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataB = ModuleMetadata.CreateFromImage(peImageB); var moduleFileB = dir.CreateFile("B.dll").WriteAllBytes(peImageB); var pdbFileB = dir.CreateFile("B.pdb").WriteAllBytes(pdbImageB); var moduleIdB = moduleMetadataB.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var documentA) = AddDefaultTestProject(solution, source1); var projectA = documentA.Project; var projectB = solution.AddProject("B", "A", "C#").AddMetadataReferences(projectA.MetadataReferences).AddDocument("DocB", source1, filePath: "DocB.cs").Project; solution = projectB.Solution; _mockCompilationOutputsProvider = project => (project.Id == projectA.Id) ? new CompilationOutputFiles(moduleFileA.Path, pdbFileA.Path) : (project.Id == projectB.Id) ? new CompilationOutputFiles(moduleFileB.Path, pdbFileB.Path) : throw ExceptionUtilities.UnexpectedValue(project); // only module A is loaded LoadLibraryToDebuggee(moduleIdA); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // // First update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); var deltaA = updates.Updates.Single(d => d.Module == moduleIdA); var deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); var baselineA0 = newBaselineA1.GetInitialEmitBaseline(); var baselineB0 = newBaselineB1.GetInitialEmitBaseline(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(4, readers.Length); Assert.False(readers.Any(r => r is null)); Assert.Equal(moduleIdA, newBaselineA1.OriginalMetadata.GetModuleVersionId()); Assert.Equal(moduleIdB, newBaselineB1.OriginalMetadata.GetModuleVersionId()); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // verify that baseline is added for both modules: Assert.Same(newBaselineA1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); EnterBreakState(debuggingSession); // // Second update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); deltaA = updates.Updates.Single(d => d.Module == moduleIdA); deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); Assert.NotSame(newBaselineA1, newBaselineA2); Assert.NotSame(newBaselineB1, newBaselineB2); Assert.Same(baselineA0, newBaselineA2.GetInitialEmitBaseline()); Assert.Same(baselineB0, newBaselineB2.GetInitialEmitBaseline()); Assert.Same(baselineA0.OriginalMetadata, newBaselineA2.OriginalMetadata); Assert.Same(baselineB0.OriginalMetadata, newBaselineB2.OriginalMetadata); // no new module readers: var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // module readers tracked: baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); // verify that baseline is updated for both modules: Assert.Same(newBaselineA2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); EndDebuggingSession(debuggingSession); // open deferred module readers should be dispose when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task BreakMode_ValidSignificantChange_BaselineCreationFailed_NoStream() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => null, OpenAssemblyStreamImpl = () => null, }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document1.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-pdb", new FileNotFoundException().Message)}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); } [Fact] public async Task BreakMode_ValidSignificantChange_BaselineCreationFailed_AssemblyReadError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll, assemblyName: "lib"); var pdbStream = new MemoryStream(); var peImage = compilationV1.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), pdbStream: pdbStream); pdbStream.Position = 0; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => pdbStream, OpenAssemblyStreamImpl = () => throw new IOException("*message*"), }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-assembly", "*message*")}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } [Fact] public async Task ActiveStatements() { var sourceV1 = "class C { void F() { G(1); } void G(int a) => System.Console.WriteLine(1); }"; var sourceV2 = "class C { int x; void F() { G(2); G(1); } void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1);"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var activeSpan21 = GetSpan(sourceV2, "G(2); G(1);"); var activeSpan22 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var adjustedActiveSpan1 = GetSpan(sourceV2, "G(2);"); var adjustedActiveSpan2 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var documentId = document1.Id; var documentPath = document1.FilePath; var sourceTextV1 = document1.GetTextSynchronously(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var activeLineSpan21 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan21); var activeLineSpan22 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan22); var adjustedActiveLineSpan1 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan1); var adjustedActiveLineSpan2 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // default if not called in a break state Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None)).IsDefault); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentPath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentPath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var activeStatementSpan11 = new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan12 = new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); AssertEx.Equal(new[] { activeStatementSpan11, activeStatementSpan12 }, baseSpans.Single()); var trackedActiveSpans1 = ImmutableArray.Create(activeStatementSpan11, activeStatementSpan12); var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document1, (_, _, _) => new(trackedActiveSpans1), CancellationToken.None); AssertEx.Equal(trackedActiveSpans1, currentSpans); Assert.Equal(activeLineSpan11, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction1, CancellationToken.None)); Assert.Equal(activeLineSpan12, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction2, CancellationToken.None)); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // tracking span update triggered by the edit: var activeStatementSpan21 = new ActiveStatementSpan(0, activeLineSpan21, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan22 = new ActiveStatementSpan(1, activeLineSpan22, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var trackedActiveSpans2 = ImmutableArray.Create(activeStatementSpan21, activeStatementSpan22); currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => new(trackedActiveSpans2), CancellationToken.None); AssertEx.Equal(new[] { adjustedActiveLineSpan1, adjustedActiveLineSpan2 }, currentSpans.Select(s => s.LineSpan)); Assert.Equal(adjustedActiveLineSpan1, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction1, CancellationToken.None)); Assert.Equal(adjustedActiveLineSpan2, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction2, CancellationToken.None)); } [Theory] [CombinatorialData] public async Task ActiveStatements_SyntaxErrorOrOutOfSyncDocument(bool isOutOfSync) { var sourceV1 = "class C { void F() => G(1); void G(int a) => System.Console.WriteLine(1); }"; // syntax error (missing ';') unless testing out-of-sync document var sourceV2 = isOutOfSync ? "class C { int x; void F() => G(1); void G(int a) => System.Console.WriteLine(2); }" : "class C { int x void F() => G(1); void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1)"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var documentId = document1.Id; var documentFilePath = document1.FilePath; var sourceTextV1 = await document1.GetTextAsync(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var debuggingSession = await StartDebuggingSessionAsync( service, solution, isOutOfSync ? CommittedSolution.DocumentState.OutOfSync : CommittedSolution.DocumentState.MatchesBuildOutput); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentFilePath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentFilePath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var baseSpans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null), new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null) }, baseSpans); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // no adjustments made due to syntax error or out-of-sync document: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), CancellationToken.None); AssertEx.Equal(new[] { activeLineSpan11, activeLineSpan12 }, currentSpans.Select(s => s.LineSpan)); var currentSpan1 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction1, CancellationToken.None); var currentSpan2 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction2, CancellationToken.None); if (isOutOfSync) { Assert.Equal(baseSpans[0].LineSpan, currentSpan1.Value); Assert.Equal(baseSpans[1].LineSpan, currentSpan2.Value); } else { Assert.Null(currentSpan1); Assert.Null(currentSpan2); } } [Fact] public async Task ActiveStatements_ForeignDocument() { var composition = FeaturesTestCompositions.Features.AddParts(typeof(DummyLanguageService)); using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(Guid.Empty, token: 0x06000001, version: 1), ilOffset: 0), documentName: document.Name, sourceSpan: new SourceSpan(0, 1, 0, 2), ActiveStatementFlags.IsNonLeafFrame)); EnterBreakState(debuggingSession, activeStatements); // active statements are not tracked in non-Roslyn projects: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None); Assert.Empty(currentSpans); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); Assert.Empty(baseSpans.Single()); } [Fact, WorkItem(24320, "https://github.com/dotnet/roslyn/issues/24320")] public async Task ActiveStatements_LinkedDocuments() { var markedSources = new[] { @"class Test1 { static void Main() => <AS:2>Project2::Test1.F();</AS:2> static void F() => <AS:1>Project4::Test2.M();</AS:1> }", @"class Test2 { static void M() => <AS:0>Console.WriteLine();</AS:0> }" }; var module1 = Guid.NewGuid(); var module2 = Guid.NewGuid(); var module4 = Guid.NewGuid(); var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 1 }, modules: new[] { module4, module2, module1 }); // Project1: Test1.cs, Test2.cs // Project2: Test1.cs (link from P1) // Project3: Test1.cs (link from P1) // Project4: Test2.cs (link from P1) using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var documents = solution.Projects.Single().Documents; var doc1 = documents.First(); var doc2 = documents.Skip(1).First(); var text1 = await doc1.GetTextAsync(); var text2 = await doc2.GetTextAsync(); DocumentId AddProjectAndLinkDocument(string projectName, Document doc, SourceText text) { var p = solution.AddProject(projectName, projectName, "C#"); var linkedDocId = DocumentId.CreateNewId(p.Id, projectName + "->" + doc.Name); solution = p.Solution.AddDocument(linkedDocId, doc.Name, text, filePath: doc.FilePath); return linkedDocId; } var docId3 = AddProjectAndLinkDocument("Project2", doc1, text1); var docId4 = AddProjectAndLinkDocument("Project3", doc1, text1); var docId5 = AddProjectAndLinkDocument("Project4", doc2, text2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, debugInfos); // Base Active Statements var baseActiveStatementsMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); var documentMap = baseActiveStatementsMap.DocumentPathMap; Assert.Equal(2, documentMap.Count); AssertEx.Equal(new[] { $"2: {doc1.FilePath}: (2,32)-(2,52) flags=[MethodUpToDate, IsNonLeafFrame]", $"1: {doc1.FilePath}: (3,29)-(3,49) flags=[MethodUpToDate, IsNonLeafFrame]" }, documentMap[doc1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"0: {doc2.FilePath}: (0,39)-(0,59) flags=[IsLeafFrame, MethodUpToDate]", }, documentMap[doc2.FilePath].Select(InspectActiveStatement)); Assert.Equal(3, baseActiveStatementsMap.InstructionMap.Count); var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module4, s.InstructionId.Method.Module); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(module2, s.InstructionId.Method.Module); s = statements[2]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module1, s.InstructionId.Method.Module); var spans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(doc1.Id, doc2.Id, docId3, docId4, docId5), CancellationToken.None); AssertEx.Equal(new[] { "(2,32)-(2,52), (3,29)-(3,49)", // test1.cs "(0,39)-(0,59)", // test2.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(0,39)-(0,59)" // link test2.cs }, spans.Select(docSpans => string.Join(", ", docSpans.Select(span => span.LineSpan)))); } [Fact] public async Task ActiveStatements_OutOfSyncDocuments() { var markedSource1 = @"class C { static void M() { try { } catch (Exception e) { <AS:0>M();</AS:0> } } }"; var source2 = @"class C { static void M() { try { } catch (Exception e) { M(); } } }"; var markedSources = new[] { markedSource1 }; var thread1 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0 leaf) var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1 }, ilOffsets: new[] { 1 }, flags: new[] { ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var project = solution.Projects.Single(); var document = project.Documents.Single(); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.OutOfSync); EnterBreakState(debuggingSession, debugInfos); // update document to test a changed solution solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); document = solution.GetDocument(document.Id); var baseActiveStatementMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements - available in out-of-sync documents, as they reflect the state of the debuggee and not the base document content Assert.Single(baseActiveStatementMap.DocumentPathMap); AssertEx.Equal(new[] { $"0: {document.FilePath}: (9,18)-(9,22) flags=[IsLeafFrame, MethodUpToDate]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(1, baseActiveStatementMap.InstructionMap.Count); var activeStatement1 = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).Single(); Assert.Equal(0x06000001, activeStatement1.InstructionId.Method.Token); Assert.Equal(document.FilePath, activeStatement1.FilePath); Assert.True(activeStatement1.IsLeaf); // Active statement reported as unchanged as the containing document is out-of-sync: var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(9,18)-(9,22)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); // Whether or not an active statement is in an exception region is unknown if the document is out-of-sync: Assert.Null(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); // Document got synchronized: debuggingSession.LastCommittedSolution.Test_SetDocumentState(document.Id, CommittedSolution.DocumentState.MatchesBuildOutput); // New location of the active statement reported: baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(10,12)-(10,16)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); Assert.True(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); } [Fact] public async Task ActiveStatements_SourceGeneratedDocuments_LineDirectives() { var markedSource1 = @" /* GENERATE: class C { void F() { #line 1 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var markedSource2 = @" /* GENERATE: class C { void F() { #line 2 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var source1 = ActiveStatementsDescription.ClearTags(markedSource1); var source2 = ActiveStatementsDescription.ClearTags(markedSource2); var additionalFileSourceV1 = @" xxxxxxxxxxxxxxxxx "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator, additionalFileText: additionalFileSourceV1); var generatedDocument1 = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync().ConfigureAwait(false)).Single(); var moduleId = EmitLibrary(source1, generator: generator, additionalFileText: additionalFileSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { GetGeneratedCodeFromMarkedSource(markedSource1) }, filePaths: new[] { generatedDocument1.FilePath }, modules: new[] { moduleId }, methodRowIds: new[] { 1 }, methodVersions: new[] { 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame })); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); AssertEx.Equal(new[] { "a.razor: [0 -> 1]" }, delta.SequencePoints.Inspect()); EndDebuggingSession(debuggingSession); } /// <summary> /// Scenario: /// F5 a program that has function F that calls G. G has a long-running loop, which starts executing. /// The user makes following operations: /// 1) Break, edit F from version 1 to version 2, continue (change is applied), G is still running in its loop /// Function remapping is produced for F v1 -> F v2. /// 2) Hot-reload edit F (without breaking) to version 3. /// Function remapping is produced for F v2 -> F v3 based on the last set of active statements calculated for F v2. /// Assume that the execution did not progress since the last resume. /// These active statements will likely not match the actual runtime active statements, /// however F v2 will never be remapped since it was hot-reloaded and not EnC'd. /// This remapping is needed for mapping from F v1 to F v3. /// 3) Break. Update F to v4. /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakStateRemappingFollowedUpByRunStateUpdate() { var markedSourceV1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { /*insert1[1]*/B();/*insert2[5]*/B();/*insert3[10]*/B(); <AS:1>G();</AS:1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var markedSourceV4 = Update(markedSourceV3, marker: "3"); var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSourceV1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSourceV1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // EnC update F v1 -> v2 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); ExitBreakState(); // Hot Reload update F v2 -> v3 solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV3), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); // EnC update F v3 -> v4 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, // matches F v1 modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F - not up-to-date anymore })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV4), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // TODO: https://github.com/dotnet/roslyn/issues/52100 // this is incorrect. correct value is: 0x06000003 v1 | AS (9,14)-(9,18) δ=16 AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=5" }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); ExitBreakState(); } /// <summary> /// Scenario: /// - F5 /// - edit, but not apply the edits /// - break /// </summary> [Fact] public async Task BreakInPresenceOfUnappliedChanges() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); <AS:1>G();</AS:1> } }"; var markedSource3 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); B(); <AS:1>G();</AS:1> } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Update to snapshot 2, but don't apply solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); // EnC update F v2 -> v3 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF1 = new LinePositionSpan(new LinePosition(8, 14), new LinePosition(8, 18)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span.Value); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource3), Encoding.UTF8)); // check that the active statement is mapped correctly to snapshot v3: var expectedSpanG2 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF2 = new LinePositionSpan(new LinePosition(9, 14), new LinePosition(9, 18)); span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF2, span); spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); // no rude edits: var document1 = solution.GetDocument(documentId); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (7,14)-(7,18) δ=2", }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); ExitBreakState(); } /// <summary> /// Scenario: /// - F5 /// - edit and apply edit that deletes non-leaf active statement /// - break /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakAfterRunModeChangeDeletesNonLeafActiveStatement() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Apply update: F v1 -> v2. solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // Break EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanF1 = new LinePositionSpan(new LinePosition(7, 14), new LinePosition(7, 18)); var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null), // TODO: https://github.com/dotnet/roslyn/issues/52100 // This is incorrect: the active statement shouldn't be reported since it has been deleted. // We need the debugger to mark the method version as replaced by run-mode update. new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null) }, spans); ExitBreakState(); } [Fact] public async Task MultiSession() { var source1 = "class C { void M() { System.Console.WriteLine(); } }"; var source3 = "class C { void M() { WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var tasks = Enumerable.Range(0, 10).Select(async i => { var sessionId = await encService.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: true, reportDiagnostics: true, CancellationToken.None); var solution1 = solution.WithDocumentText(documentIdA, SourceText.From("class C { void M() { System.Console.WriteLine(" + i + "); } }", Encoding.UTF8)); var result1 = await encService.EmitSolutionUpdateAsync(sessionId, solution1, s_noActiveSpans, CancellationToken.None); Assert.Empty(result1.Diagnostics); Assert.Equal(1, result1.ModuleUpdates.Updates.Length); var solution2 = solution1.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); var result2 = await encService.EmitSolutionUpdateAsync(sessionId, solution2, s_noActiveSpans, CancellationToken.None); Assert.Equal("CS0103", result2.Diagnostics.Single().Diagnostics.Single().Id); Assert.Empty(result2.ModuleUpdates.Updates); encService.EndDebuggingSession(sessionId, out var _); }); await Task.WhenAll(tasks); Assert.Empty(encService.GetTestAccessor().GetActiveDebuggingSessions()); } [Fact] public async Task WatchHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new WatchHotReloadService(workspace.Services, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition")); await hotReload.StartSessionAsync(solution, CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); AssertEx.Equal(new[] { 0x02000002 }, result.updates[0].UpdatedTypes); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); hotReload.EndSession(); } [Fact] public async Task UnitTestingHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new UnitTestingHotReloadService(workspace.Services); await hotReload.StartSessionAsync(solution, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition"), CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); hotReload.EndSession(); } [Fact] public void ParseCapabilities() { var capabilities = ImmutableArray.Create("Baseline"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.True(service.HasFlag(EditAndContinueCapabilities.Baseline)); Assert.False(service.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)); } [Fact] public void ParseCapabilities_CaseSensitive() { var capabilities = ImmutableArray.Create("BaseLine"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.False(service.HasFlag(EditAndContinueCapabilities.Baseline)); } [Fact] public void ParseCapabilities_IgnoreInvalid() { var capabilities = ImmutableArray.Create("Baseline", "Invalid", "NewTypeDefinition"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.True(service.HasFlag(EditAndContinueCapabilities.Baseline)); Assert.True(service.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)); } [Fact] public void ParseCapabilities_IgnoreInvalidNumeric() { var capabilities = ImmutableArray.Create("Baseline", "90", "NewTypeDefinition"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.True(service.HasFlag(EditAndContinueCapabilities.Baseline)); Assert.True(service.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)); } [Fact] public void ParseCapabilities_AllCapabilitiesParsed() { foreach (var name in Enum.GetNames(typeof(EditAndContinueCapabilities))) { var capabilities = ImmutableArray.Create(name); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); var flag = (EditAndContinueCapabilities)Enum.Parse(typeof(EditAndContinueCapabilities), name); Assert.True(service.HasFlag(flag), $"Capability '{name}' was not parsed correctly, so it's impossible for a runtime to enable it!"); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api; using Microsoft.CodeAnalysis.ExternalAccess.Watch.Api; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public sealed partial class EditAndContinueWorkspaceServiceTests : TestBase { private static readonly TestComposition s_composition = FeaturesTestCompositions.Features; private static readonly ActiveStatementSpanProvider s_noActiveSpans = (_, _, _) => new(ImmutableArray<ActiveStatementSpan>.Empty); private const TargetFramework DefaultTargetFramework = TargetFramework.NetStandard20; private Func<Project, CompilationOutputs> _mockCompilationOutputsProvider; private readonly List<string> _telemetryLog; private int _telemetryId; private readonly MockManagedEditAndContinueDebuggerService _debuggerService; public EditAndContinueWorkspaceServiceTests() { _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()); _telemetryLog = new List<string>(); _debuggerService = new MockManagedEditAndContinueDebuggerService() { LoadedModules = new Dictionary<Guid, ManagedEditAndContinueAvailability>() }; } private TestWorkspace CreateWorkspace(out Solution solution, out EditAndContinueWorkspaceService service, Type[] additionalParts = null) { var workspace = new TestWorkspace(composition: s_composition.AddParts(additionalParts)); solution = workspace.CurrentSolution; service = GetEditAndContinueService(workspace); return workspace; } private static SourceText GetAnalyzerConfigText((string key, string value)[] analyzerConfig) => SourceText.From("[*.*]" + Environment.NewLine + string.Join(Environment.NewLine, analyzerConfig.Select(c => $"{c.key} = {c.value}"))); private static (Solution, Document) AddDefaultTestProject( Solution solution, string source, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { solution = AddDefaultTestProject(solution, new[] { source }, generator, additionalFileText, analyzerConfig); return (solution, solution.Projects.Single().Documents.Single()); } private static Solution AddDefaultTestProject( Solution solution, string[] sources, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { var project = solution. AddProject("proj", "proj", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = project.Solution; if (generator != null) { solution = solution.AddAnalyzerReference(project.Id, new TestGeneratorReference(generator)); } if (additionalFileText != null) { solution = solution.AddAdditionalDocument(DocumentId.CreateNewId(project.Id), "additional", SourceText.From(additionalFileText)); } if (analyzerConfig != null) { solution = solution.AddAnalyzerConfigDocument( DocumentId.CreateNewId(project.Id), name: "config", GetAnalyzerConfigText(analyzerConfig), filePath: Path.Combine(TempRoot.Root, "config")); } Document document = null; var i = 1; foreach (var source in sources) { var fileName = $"test{i++}.cs"; document = solution.GetProject(project.Id). AddDocument(fileName, SourceText.From(source, Encoding.UTF8), filePath: Path.Combine(TempRoot.Root, fileName)); solution = document.Project.Solution; } return document.Project.Solution; } private EditAndContinueWorkspaceService GetEditAndContinueService(Workspace workspace) { var service = (EditAndContinueWorkspaceService)workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); var accessor = service.GetTestAccessor(); accessor.SetOutputProvider(project => _mockCompilationOutputsProvider(project)); return service; } private async Task<DebuggingSession> StartDebuggingSessionAsync( EditAndContinueWorkspaceService service, Solution solution, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var sessionId = await service.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var session = service.GetTestAccessor().GetDebuggingSession(sessionId); if (initialState != CommittedSolution.DocumentState.None) { SetDocumentsState(session, solution, initialState); } session.GetTestAccessor().SetTelemetryLogger((id, message) => _telemetryLog.Add($"{id}: {message.GetMessage()}"), () => ++_telemetryId); return session; } private void EnterBreakState( DebuggingSession session, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements = default, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { _debuggerService.GetActiveStatementsImpl = () => activeStatements.NullToEmpty(); session.BreakStateEntered(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private void ExitBreakState() { _debuggerService.GetActiveStatementsImpl = () => ImmutableArray<ManagedActiveStatementDebugInfo>.Empty; } private static void CommitSolutionUpdate(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.CommitSolutionUpdate(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static void EndDebuggingSession(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.EndSession(out var documentsToReanalyze, out _); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static async Task<(ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics)> EmitSolutionUpdateAsync( DebuggingSession session, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider = null) { var result = await session.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider ?? s_noActiveSpans, CancellationToken.None); return (result.ModuleUpdates, result.GetDiagnosticData(solution)); } internal static void SetDocumentsState(DebuggingSession session, Solution solution, CommittedSolution.DocumentState state) { foreach (var project in solution.Projects) { foreach (var document in project.Documents) { session.LastCommittedSolution.Test_SetDocumentState(document.Id, state); } } } private static IEnumerable<string> InspectDiagnostics(ImmutableArray<DiagnosticData> actual) => actual.Select(d => $"{d.ProjectId} {InspectDiagnostic(d)}"); private static string InspectDiagnostic(DiagnosticData diagnostic) => $"{diagnostic.Severity} {diagnostic.Id}: {diagnostic.Message}"; internal static Guid ReadModuleVersionId(Stream stream) { using var peReader = new PEReader(stream); var metadataReader = peReader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; return metadataReader.GetGuid(mvidHandle); } private Guid EmitAndLoadLibraryToDebuggee(string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "") { var moduleId = EmitLibrary(source, sourceFilePath, encoding, assemblyName); LoadLibraryToDebuggee(moduleId); return moduleId; } private void LoadLibraryToDebuggee(Guid moduleId, ManagedEditAndContinueAvailability availability = default) { _debuggerService.LoadedModules.Add(moduleId, availability); } private Guid EmitLibrary( string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { return EmitLibrary(new[] { (source, sourceFilePath ?? Path.Combine(TempRoot.Root, "test1.cs")) }, encoding, assemblyName, pdbFormat, generator, additionalFileText, analyzerOptions); } private Guid EmitLibrary( (string content, string filePath)[] sources, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { encoding ??= Encoding.UTF8; var parseOptions = TestOptions.RegularPreview; var trees = sources.Select(source => { var sourceText = SourceText.From(new MemoryStream(encoding.GetBytes(source.content)), encoding, checksumAlgorithm: SourceHashAlgorithm.Sha256); return SyntaxFactory.ParseSyntaxTree(sourceText, parseOptions, source.filePath); }); Compilation compilation = CSharpTestBase.CreateCompilation(trees.ToArray(), options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: assemblyName); if (generator != null) { var optionsProvider = (analyzerOptions != null) ? new EditAndContinueTestAnalyzerConfigOptionsProvider(analyzerOptions) : null; var additionalTexts = (additionalFileText != null) ? new[] { new InMemoryAdditionalText("additional_file", additionalFileText) } : null; var generatorDriver = CSharpGeneratorDriver.Create(new[] { generator }, additionalTexts, parseOptions, optionsProvider); generatorDriver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); generatorDiagnostics.Verify(); compilation = outputCompilation; } return EmitLibrary(compilation, pdbFormat); } private Guid EmitLibrary(Compilation compilation, DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb) { var (peImage, pdbImage) = compilation.EmitToArrays(new EmitOptions(debugInformationFormat: pdbFormat)); var symReader = SymReaderTestHelpers.OpenDummySymReader(pdbImage); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleId = moduleMetadata.GetModuleVersionId(); // associate the binaries with the project (assumes a single project) _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenAssemblyStreamImpl = () => { var stream = new MemoryStream(); peImage.WriteToStream(stream); stream.Position = 0; return stream; }, OpenPdbStreamImpl = () => { var stream = new MemoryStream(); pdbImage.WriteToStream(stream); stream.Position = 0; return stream; } }; return moduleId; } private static SourceText CreateSourceTextFromFile(string path) { using var stream = File.OpenRead(path); return SourceText.From(stream, Encoding.UTF8, SourceHashAlgorithm.Sha256); } private static TextSpan GetSpan(string str, string substr) => new TextSpan(str.IndexOf(substr), substr.Length); private static void VerifyReadersDisposed(IEnumerable<IDisposable> readers) { foreach (var reader in readers) { Assert.Throws<ObjectDisposedException>(() => { if (reader is MetadataReaderProvider md) { md.GetMetadataReader(); } else { ((DebugInformationReaderProvider)reader).CreateEditAndContinueMethodDebugInfoReader(); } }); } } private static DocumentInfo CreateDesignTimeOnlyDocument(ProjectId projectId, string name = "design-time-only.cs", string path = "design-time-only.cs") => DocumentInfo.Create( DocumentId.CreateNewId(projectId, name), name: name, folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class DTO {}"), VersionStamp.Create(), path)), filePath: path, isGenerated: false, designTimeOnly: true, documentServiceProvider: null); internal sealed class FailingTextLoader : TextLoader { public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { Assert.True(false, $"Content of document {documentId} should never be loaded"); throw ExceptionUtilities.Unreachable; } } [Theory] [CombinatorialData] public async Task StartDebuggingSession_CapturingDocuments(bool captureAllDocuments) { var encodingA = Encoding.BigEndianUnicode; var encodingB = Encoding.Unicode; var encodingC = Encoding.GetEncoding("SJIS"); var encodingE = Encoding.UTF8; var sourceA1 = "class A {}"; var sourceB1 = "class B { int F() => 1; }"; var sourceB2 = "class B { int F() => 2; }"; var sourceB3 = "class B { int F() => 3; }"; var sourceC1 = "class C { const char L = 'ワ'; }"; var sourceD1 = "dummy code"; var sourceE1 = "class E { }"; var sourceBytesA1 = encodingA.GetBytes(sourceA1); var sourceBytesB1 = encodingB.GetBytes(sourceB1); var sourceBytesC1 = encodingC.GetBytes(sourceC1); var sourceBytesE1 = encodingE.GetBytes(sourceE1); var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllBytes(sourceBytesA1); var sourceFileB = dir.CreateFile("B.cs").WriteAllBytes(sourceBytesB1); var sourceFileC = dir.CreateFile("C.cs").WriteAllBytes(sourceBytesC1); var sourceFileD = dir.CreateFile("dummy").WriteAllText(sourceD1); var sourceFileE = dir.CreateFile("E.cs").WriteAllBytes(sourceBytesE1); var sourceTreeA1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesA1, sourceBytesA1.Length, encodingA, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileA.Path); var sourceTreeB1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesB1, sourceBytesB1.Length, encodingB, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileB.Path); var sourceTreeC1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesC1, sourceBytesC1.Length, encodingC, SourceHashAlgorithm.Sha1), TestOptions.Regular, sourceFileC.Path); // E is not included in the compilation: var compilation = CSharpTestBase.CreateCompilation(new[] { sourceTreeA1, sourceTreeB1, sourceTreeC1 }, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "P"); EmitLibrary(compilation); // change content of B on disk: sourceFileB.WriteAllText(sourceB2, encodingB); // prepare workspace as if it was loaded from project files: using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var projectP = solution.AddProject("P", "P", LanguageNames.CSharp); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, encodingA), filePath: sourceFileA.Path)); var documentIdB = DocumentId.CreateNewId(projectP.Id, debugName: "B"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdB, name: "B", loader: new FileTextLoader(sourceFileB.Path, encodingB), filePath: sourceFileB.Path)); var documentIdC = DocumentId.CreateNewId(projectP.Id, debugName: "C"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdC, name: "C", loader: new FileTextLoader(sourceFileC.Path, encodingC), filePath: sourceFileC.Path)); var documentIdE = DocumentId.CreateNewId(projectP.Id, debugName: "E"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdE, name: "E", loader: new FileTextLoader(sourceFileE.Path, encodingE), filePath: sourceFileE.Path)); // check that are testing documents whose hash algorithm does not match the PDB (but the hash itself does): Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdA).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdB).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdC).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdE).GetTextSynchronously(default).ChecksumAlgorithm); // design-time-only document with and without absolute path: solution = solution. AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt1.cs", path: Path.Combine(dir.Path, "dt1.cs"))). AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt2.cs", path: "dt2.cs")); // project that does not support EnC - the contents of documents in this project shouldn't be loaded: var projectQ = solution.AddProject("Q", "Q", DummyLanguageService.LanguageName); solution = projectQ.Solution; solution = solution.AddDocument(DocumentInfo.Create( id: DocumentId.CreateNewId(projectQ.Id, debugName: "D"), name: "D", loader: new FailingTextLoader(), filePath: sourceFileD.Path)); var captureMatchingDocuments = captureAllDocuments ? ImmutableArray<DocumentId>.Empty : (from project in solution.Projects from documentId in project.DocumentIds select documentId).ToImmutableArray(); var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments, captureAllDocuments, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = debuggingSession.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)", "(C, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // change content of B on disk again: sourceFileB.WriteAllText(sourceB3, encodingB); solution = solution.WithDocumentTextLoader(documentIdB, new FileTextLoader(sourceFileB.Path, encodingB), PreservationMode.PreserveValue); EnterBreakState(debuggingSession); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{projectP.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFileB.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); } [Fact] public async Task RunMode_ProjectThatDoesNotSupportEnC() { using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; await StartDebuggingSessionAsync(service, solution); // no changes: var document1 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("dummy2")); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task RunMode_DesignTimeOnlyDocument() { var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); var documentInfo = CreateDesignTimeOnlyDocument(document1.Project.Id); solution = solution.WithProjectOutputFilePath(document1.Project.Id, moduleFile.Path).AddDocument(documentInfo); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update a design-time-only source file: solution = solution.WithDocumentText(documentInfo.Id, SourceText.From("class UpdatedC2 {}")); var document2 = solution.GetDocument(documentInfo.Id); // no updates: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // validate solution update status and emit - changes made in design-time-only documents are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0" }, _telemetryLog); } [Fact] public async Task RunMode_ProjectNotBuilt() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.Empty); await StartDebuggingSessionAsync(service, solution); // no changes: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task RunMode_DifferentDocumentWithSameContent() { var source = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source); solution = solution.WithProjectOutputFilePath(document.Project.Id, moduleFile.Path); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update the document var document1 = solution.GetDocument(document.Id); solution = solution.WithDocumentText(document.Id, SourceText.From(source)); var document2 = solution.GetDocument(document.Id); Assert.Equal(document1.Id, document2.Id); Assert.NotSame(document1, document2); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); // validate solution update status and emit - changes made during run mode are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0" }, _telemetryLog); } [Fact] public async Task BreakMode_ProjectThatDoesNotSupportEnC() { using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("dummy2")); var document2 = solution.GetDocument(document1.Id); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); } [Fact] public async Task BreakMode_DesignTimeOnlyDocument_Dynamic() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C {}"); var documentInfo = DocumentInfo.Create( DocumentId.CreateNewId(document.Project.Id), name: "design-time-only.cs", folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class D {}"), VersionStamp.Create(), "design-time-only.cs")), filePath: "design-time-only.cs", isGenerated: false, designTimeOnly: true, documentServiceProvider: null); solution = solution.AddDocument(documentInfo); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.GetDocument(documentInfo.Id); solution = solution.WithDocumentText(document1.Id, SourceText.From("class E {}")); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_DesignTimeOnlyDocument_Wpf(bool delayLoad) { var sourceA = "class A { public void M() { } }"; var sourceB = "class B { public void M() { } }"; var sourceC = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("a.cs").WriteAllText(sourceA); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); var documentB = documentA.Project. AddDocument("b.g.i.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: "b.g.i.cs"); var documentC = documentB.Project. AddDocument("c.g.i.vb", SourceText.From(sourceC, Encoding.UTF8), filePath: "c.g.i.vb"); solution = documentC.Project.Solution; // only compile A; B and C are design-time-only: var moduleId = EmitLibrary(sourceA, sourceFilePath: sourceFileA.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); EnterBreakState(debuggingSession); // change the source (rude edit): solution = solution.WithDocumentText(documentB.Id, SourceText.From("class B { public void RenamedMethod() { } }")); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { public void RenamedMethod() { } }")); var documentB2 = solution.GetDocument(documentB.Id); var documentC2 = solution.GetDocument(documentC.Id); // no Rude Edits reported: Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentB2, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentC2, s_noActiveSpans, CancellationToken.None)); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); if (delayLoad) { LoadLibraryToDebuggee(moduleId); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); } EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task ErrorReadingModuleFile(bool breakMode) { // module file is empty, which will cause a read error: var moduleFile = Temp.CreateFile(); string expectedErrorMessage = null; try { using var stream = File.OpenRead(moduleFile.Path); using var peReader = new PEReader(stream); _ = peReader.GetMetadataReader(); } catch (Exception e) { expectedErrorMessage = e.Message; } using var _w = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, moduleFile.Path, expectedErrorMessage)}" }, InspectDiagnostics(emitDiagnostics)); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0", }, _telemetryLog); } } [Fact] public async Task BreakMode_ErrorReadingPdbFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenPdbStreamImpl = () => { throw new IOException("Error"); } }; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=1" }, _telemetryLog); } [Fact] public async Task BreakMode_ErrorReadingSourceFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); using var fileLock = File.Open(sourceFile.Path, FileMode.Open, FileAccess.Read, FileShare.None); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // try apply changes: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); fileLock.Dispose(); // try apply changes again: (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.NotEmpty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0" }, _telemetryLog); } [Theory] [CombinatorialData] public async Task FileAdded(bool breakMode) { var sourceA = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceB = "class C2 {}"; var sourceFileA = Temp.CreateFile().WriteAllText(sourceA); var sourceFileB = Temp.CreateFile().WriteAllText(sourceB); using var _ = CreateWorkspace(out var solution, out var service); var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); solution = documentA.Project.Solution; // Source B will be added while debugging. EmitAndLoadLibraryToDebuggee(sourceA, sourceFilePath: sourceFileA.Path); var project = documentA.Project; var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // add a source file: var documentB = project.AddDocument("file2.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: sourceFileB.Path); solution = documentB.Project.Solution; documentB = solution.GetDocument(documentB.Id); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(documentB, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0" }, _telemetryLog); } } [Fact] public async Task BreakMode_ModuleDisallowsEditAndContinue() { var moduleId = Guid.NewGuid(); var source1 = @" class C1 { void M() { System.Console.WriteLine(1); System.Console.WriteLine(2); System.Console.WriteLine(3); } }"; var source2 = @" class C1 { void M() { System.Console.WriteLine(9); System.Console.WriteLine(); System.Console.WriteLine(30); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); LoadLibraryToDebuggee(moduleId, new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForRuntime, "*message*")); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // We do not report module diagnostics until emit. // This is to make the analysis deterministic (not dependent on the current state of the debuggee). var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC2016: {string.Format(FeaturesResources.EditAndContinueDisallowedByProject, document2.Project.Name, "*message*")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC2016" }, _telemetryLog); } [Fact] public async Task BreakMode_Encodings() { var source1 = "class C1 { void M() { System.Console.WriteLine(\"ã\"); } }"; var encoding = Encoding.GetEncoding(1252); var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1, encoding); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, encoding), filePath: sourceFile.Path); var documentId = document1.Id; var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path, encoding: encoding); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // Emulate opening the file, which will trigger "out-of-sync" check. // Since we find content matching the PDB checksum we update the committed solution with this source text. // If we used wrong encoding this would lead to a false change detected below. var currentDocument = solution.GetDocument(documentId); await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); // EnC service queries for a document, which triggers read of the source file from disk. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task RudeEdits(bool breakMode) { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0", }, _telemetryLog); } } [Fact] public async Task BreakMode_RudeEdits_SourceGenerators() { var sourceV1 = @" /* GENERATE: class G { int X1 => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X2 => 1; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1, generator: generator); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var generatedDocument = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync()).Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(generatedDocument, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.property_) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(generatedDocument.Id)); } [Theory] [CombinatorialData] public async Task RudeEdits_DocumentOutOfSync(bool breakMode) { var source0 = "class C1 { void M() { System.Console.WriteLine(0); } }"; var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void RenamedMethod() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs"); using var _ = CreateWorkspace(out var solution, out var service); var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; // compile with source0: var moduleId = EmitAndLoadLibraryToDebuggee(source0, sourceFilePath: sourceFile.Path); // update the file with source1 before session starts: sourceFile.WriteAllText(source1); // source1 is reflected in workspace before session starts: var document1 = project.AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); solution = document1.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // no Rude Edits, since the document is out-of-sync var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // update the file to match the build: sourceFile.WriteAllText(source0); // we do not reload the content of out-of-sync file for analyzer query: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // debugger query will trigger reload of out-of-sync file content: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // now we see the rude edit: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0", }, _telemetryLog); } } [Fact] public async Task BreakMode_RudeEdits_DocumentWithoutSequencePoints() { var source1 = "abstract class C { public abstract void M(); }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit since the base document content matches the PDB checksum, so the document is not out-of-sync): solution = solution.WithDocumentText(document1.Id, SourceText.From("abstract class C { public abstract void M(); public abstract void N(); }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0023: " + string.Format(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task BreakMode_RudeEdits_DelayLoadedModule() { var source1 = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit) before the library is loaded: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C { public void Renamed() { } }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // load library to the debuggee: LoadLibraryToDebuggee(moduleId); // Rude Edits still reported: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task BreakMode_SyntaxError() { var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { ")); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=True|HadRudeEdits=False|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0" }, _telemetryLog); } [Fact] public async Task BreakMode_SemanticError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { int i = 0L; System.Console.WriteLine(i); } }", Encoding.UTF8)); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // The EnC analyzer does not check for and block on all semantic errors as they are already reported by diagnostic analyzer. // Blocking update on semantic errors would be possible, but the status check is only an optimization to avoid emitting. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); // TODO: https://github.com/dotnet/roslyn/issues/36061 // Semantic errors should not be reported in emit diagnostics. AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS0266: {string.Format(CSharpResources.ERR_NoImplicitConvCast, "long", "int")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS0266" }, _telemetryLog); } [Fact] public async Task BreakMode_FileStatus_CompilationError() { using var _ = CreateWorkspace(out var solution, out var service); solution = solution. AddProject("A", "A", "C#"). AddDocument("A.cs", "class Program { void Main() { System.Console.WriteLine(1); } }", filePath: "A.cs").Project.Solution. AddProject("B", "B", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("B.cs", "class B {}", filePath: "B.cs").Project.Solution. AddProject("C", "C", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("C.cs", "class C {}", filePath: "C.cs").Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change C.cs to have a compilation error: var projectC = solution.GetProjectsByName("C").Single(); var documentC = projectC.Documents.Single(d => d.Name == "C.cs"); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { void M() { ")); // Common.cs is included in projects B and C. Both of these projects must have no errors, otherwise update is blocked. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "Common.cs", CancellationToken.None)); // No changes in project containing file B.cs. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "B.cs", CancellationToken.None)); // All projects must have no errors. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_EmitError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit but passing no encoding to emulate emit error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", encoding: null)); var document2 = solution.Projects.Single().Documents.Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS8055: {string.Format(CSharpResources.ERR_EncodinglessSyntaxTree)}" }, InspectDiagnostics(emitDiagnostics)); // no emitted delta: Assert.Empty(updates.Updates); // no pending update: Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); Assert.Throws<InvalidOperationException>(() => debuggingSession.CommitSolutionUpdate(out var _)); Assert.Throws<InvalidOperationException>(() => debuggingSession.DiscardSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // solution update status after discarding an update (still has update ready): Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS8055" }, _telemetryLog); } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_ValidSignificantChange_ApplyBeforeFileWatcherEvent(bool saveDocument) { // Scenarios tested: // // SaveDocument=true // workspace: --V0-------------|--V2--------|------------| // file system: --V0---------V1--|-----V2-----|------------| // \--build--/ F5 ^ F10 ^ F10 // save file watcher: no-op // SaveDocument=false // workspace: --V0-------------|--V2--------|----V1------| // file system: --V0---------V1--|------------|------------| // \--build--/ F5 F10 ^ F10 // file watcher: workspace update var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var documentId = document1.Id; solution = document1.Project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // The user opens the source file and changes the source before Roslyn receives file watcher event. var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(documentId); // Save the document: if (saveDocument) { await debuggingSession.OnSourceFileUpdatedAsync(document2); sourceFile.WriteAllText(source2); } // EnC service queries for a document, which triggers read of the source file from disk. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); ExitBreakState(); EnterBreakState(debuggingSession); // file watcher updates the workspace: solution = solution.WithDocumentText(documentId, CreateSourceTextFromFile(sourceFile.Path)); var document3 = solution.Projects.Single().Documents.Single(); var hasChanges = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); if (saveDocument) { Assert.False(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); } else { Assert.True(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); } ExitBreakState(); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_FileUpdateNotObservedBeforeDebuggingSessionStart() { // workspace: --V0--------------V2-------|--------V3------------------V1--------------| // file system: --V0---------V1-----V2-----|------------------------------V1------------| // \--build--/ ^save F5 ^ ^F10 (no change) ^save F10 (ok) // file watcher: no-op // build updates file from V0 -> V1 var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C1 { void M() { System.Console.WriteLine(3); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source2); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document2 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source2, Encoding.UTF8), filePath: sourceFile.Path); var documentId = document2.Id; var project = document2.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // user edits the file: solution = solution.WithDocumentText(documentId, SourceText.From(source3, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); // EnC service queries for a document, but the source file on disk doesn't match the PDB // We don't report rude edits for out-of-sync documents: var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // undo: solution = solution.WithDocumentText(documentId, SourceText.From(source1, Encoding.UTF8)); var currentDocument = solution.GetDocument(documentId); // save (note that this call will fail to match the content with the PDB since it uses the content prior to the actual file write) await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); var (doc, state) = await debuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(documentId, currentDocument, CancellationToken.None); Assert.Null(doc); Assert.Equal(CommittedSolution.DocumentState.OutOfSync, state); sourceFile.WriteAllText(source1); Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); // the content actually hasn't changed: Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_AddedFileNotObservedBeforeDebuggingSessionStart() { // workspace: ------|----V0---------------|---------- // file system: --V0--|---------------------|---------- // F5 ^ ^F10 (no change) // file watcher observes the file var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with no file var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _debuggerService.IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Attach, localizedMessage: "*attached*"); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); // An active statement may be present in the added file since the file exists in the PDB: var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeSpan1 = GetSpan(source1, "System.Console.WriteLine(1);"); var sourceText1 = SourceText.From(source1, Encoding.UTF8); var activeLineSpan1 = sourceText1.Lines.GetLinePositionSpan(activeSpan1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, "test.cs", activeLineSpan1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); // disallow any edits (attach scenario) EnterBreakState(debuggingSession, activeStatements); // File watcher observes the document and adds it to the workspace: var document1 = project.AddDocument("test.cs", sourceText1, filePath: sourceFile.Path); solution = document1.Project.Solution; // We don't report rude edits for the added document: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // TODO: https://github.com/dotnet/roslyn/issues/49938 // We currently create the AS map against the committed solution, which may not contain all documents. // var spans = await service.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); // AssertEx.Equal(new[] { $"({activeLineSpan1}, IsLeafFrame)" }, spans.Single().Select(s => s.ToString())); // No changes. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task BreakMode_ValidSignificantChange_DocumentOutOfSync(bool delayLoad) { var sourceOnDisk = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(sourceOnDisk); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(sourceOnDisk, sourceFilePath: sourceFile.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // no changes have been made to the project Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // a file watcher observed a change and updated the document, so it now reflects the content on disk (the code that we compiled): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceOnDisk, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // the content of the file is now exactly the same as the compiled document, so there is no change to be applied: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); Assert.Empty(debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); } [Theory] [CombinatorialData] public async Task ValidSignificantChange_EmitSuccessful(bool breakMode, bool commitUpdate) { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceV2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); void ValidateDelta(ManagedModuleUpdate delta) { // check emitted delta: Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000001, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); } // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); AssertEx.Equal(updates.Updates, pendingUpdate.Deltas); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); if (commitUpdate) { // all update providers either provided updates or had no change to apply: CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, baselineReaders.Length); Assert.Same(readers[0], baselineReaders[0]); Assert.Same(readers[1], baselineReaders[1]); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: var commitedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.False(commitedUpdateSolutionStatus); } else { // another update provider blocked the update: debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // solution update status after committing an update: var discardedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.True(discardedUpdateSolutionStatus); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); } if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0", }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0", }, _telemetryLog); } } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_ValidSignificantChange_EmitSuccessful_UpdateDeferred(bool commitUpdate) { var dir = Temp.CreateDirectory(); var sourceV1 = "class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilation(sourceV1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "lib"); var (peImage, pdbImage) = compilationV1.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleFile = dir.CreateFile("lib.dll").WriteAllBytes(peImage); var pdbFile = dir.CreateFile("lib.pdb").WriteAllBytes(pdbImage); var moduleId = moduleMetadata.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path, pdbFile.Path); // set up an active statement in the first method, so that we can test preservation of local signature. var activeStatements = ImmutableArray.Create(new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 0), documentName: document1.Name, sourceSpan: new SourceSpan(0, 15, 0, 16), ActiveStatementFlags.IsLeafFrame)); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module is not loaded: EnterBreakState(debuggingSession, activeStatements); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); // delta to apply: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000002, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); if (commitUpdate) { CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); // make another update: EnterBreakState(debuggingSession); // Update M1 - this method has an active statement, so we will attempt to preserve the local signature. // Since the method hasn't been edited before we'll read the baseline PDB to get the signature token. // This validates that the Portable PDB reader can be used (and is not disposed) for a second generation edit. var document3 = solution.GetDocument(document1.Id); solution = solution.WithDocumentText(document3.Id, SourceText.From("class C1 { void M1() { int a = 3; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); } else { debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); } ExitBreakState(); EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task BreakMode_ValidSignificantChange_PartialTypes() { var sourceA1 = @" partial class C { int X = 1; void F() { X = 1; } } partial class D { int U = 1; public D() { } } partial class D { int W = 1; } partial class E { int A; public E(int a) { A = a; } } "; var sourceB1 = @" partial class C { int Y = 1; } partial class E { int B; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; var sourceA2 = @" partial class C { int X = 2; void F() { X = 2; } } partial class D { int U = 2; } partial class D { int W = 2; public D() { } } partial class E { int A = 1; public E(int a) { A = a; } } "; var sourceB2 = @" partial class C { int Y = 2; } partial class E { int B = 2; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { sourceA1, sourceB1 }); var project = solution.Projects.Single(); LoadLibraryToDebuggee(EmitLibrary(new[] { (sourceA1, "test1.cs"), (sourceB1, "test2.cs") })); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): var documentA = project.Documents.First(); var documentB = project.Documents.Skip(1).First(); solution = solution.WithDocumentText(documentA.Id, SourceText.From(sourceA2, Encoding.UTF8)); solution = solution.WithDocumentText(documentB.Id, SourceText.From(sourceB2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(6, delta.UpdatedMethods.Length); // F, C.C(), D.D(), E.E(int), E.E(int, int), lambda AssertEx.SetEqual(new[] { 0x02000002, 0x02000003, 0x02000004, 0x02000005 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } private static EditAndContinueLogEntry Row(int rowNumber, TableIndex table, EditAndContinueOperation operation) => new(MetadataTokens.Handle(table, rowNumber), operation); private static unsafe void VerifyEncLogMetadata(ImmutableArray<byte> delta, params EditAndContinueLogEntry[] expectedRows) { fixed (byte* ptr = delta.ToArray()) { var reader = new MetadataReader(ptr, delta.Length); AssertEx.Equal(expectedRows, reader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString); } static string EncLogRowToString(EditAndContinueLogEntry row) { TableIndex tableIndex; MetadataTokens.TryGetTableIndex(row.Handle.Kind, out tableIndex); return string.Format( "Row({0}, TableIndex.{1}, EditAndContinueOperation.{2})", MetadataTokens.GetRowNumber(row.Handle), tableIndex, row.Operation); } } private static void GenerateSource(GeneratorExecutionContext context) { foreach (var syntaxTree in context.Compilation.SyntaxTrees) { var fileName = PathUtilities.GetFileName(syntaxTree.FilePath); Generate(syntaxTree.GetText().ToString(), fileName); if (context.AnalyzerConfigOptions.GetOptions(syntaxTree).TryGetValue("enc_generator_output", out var optionValue)) { context.AddSource("GeneratedFromOptions_" + fileName, $"class G {{ int X => {optionValue}; }}"); } } foreach (var additionalFile in context.AdditionalFiles) { Generate(additionalFile.GetText()!.ToString(), PathUtilities.GetFileName(additionalFile.Path)); } void Generate(string source, string fileName) { var generatedSource = GetGeneratedCodeFromMarkedSource(source); if (generatedSource != null) { context.AddSource($"Generated_{fileName}", generatedSource); } } } private static string GetGeneratedCodeFromMarkedSource(string markedSource) { const string OpeningMarker = "/* GENERATE:"; const string ClosingMarker = "*/"; var index = markedSource.IndexOf(OpeningMarker); if (index > 0) { index += OpeningMarker.Length; var closing = markedSource.IndexOf(ClosingMarker, index); return markedSource[index..closing].Trim(); } return null; } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate() { var sourceV1 = @" /* GENERATE: class G { int X => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X => 2; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(2, delta.UpdatedMethods.Length); AssertEx.Equal(new[] { 0x02000002, 0x02000003 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate_LineChanges() { var sourceV1 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var sourceV2 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); var lineUpdate = delta.SequencePoints.Single(); AssertEx.Equal(new[] { "3 -> 4" }, lineUpdate.LineUpdates.Select(edit => $"{edit.OldLine} -> {edit.NewLine}")); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentInsert() { var sourceV1 = @" partial class C { int X = 1; } "; var sourceV2 = @" /* GENERATE: partial class C { int Y = 2; } */ partial class C { int X = 1; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); // constructor update Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_AdditionalDocumentUpdate() { var source = @" class C { int Y => 1; } "; var additionalSourceV1 = @" /* GENERATE: class G { int X => 1; } */ "; var additionalSourceV2 = @" /* GENERATE: class G { int X => 2; } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, additionalFileText: additionalSourceV1); var moduleId = EmitLibrary(source, generator: generator, additionalFileText: additionalSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var additionalDocument1 = solution.Projects.Single().AdditionalDocuments.Single(); solution = solution.WithAdditionalDocumentText(additionalDocument1.Id, SourceText.From(additionalSourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_AnalyzerConfigUpdate() { var source = @" class C { int Y => 1; } "; var configV1 = new[] { ("enc_generator_output", "1") }; var configV2 = new[] { ("enc_generator_output", "2") }; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, analyzerConfig: configV1); var moduleId = EmitLibrary(source, generator: generator, analyzerOptions: configV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var configDocument1 = solution.Projects.Single().AnalyzerConfigDocuments.Single(); solution = solution.WithAnalyzerConfigDocumentText(configDocument1.Id, GetAnalyzerConfigText(configV2)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentRemove() { var source1 = ""; var generator = new TestSourceGenerator() { ExecuteImpl = context => context.AddSource("generated", $"class G {{ int X => {context.Compilation.SyntaxTrees.Count()}; }}") }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator); var moduleId = EmitLibrary(source1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // remove the source document (valid edit): solution = document1.Project.Solution.RemoveDocument(document1.Id); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } /// <summary> /// Emulates two updates to Multi-TFM project. /// </summary> [Fact] public async Task TwoUpdatesWithLoadedAndUnloadedModule() { var dir = Temp.CreateDirectory(); var source1 = "class A { void M() { System.Console.WriteLine(1); } }"; var source2 = "class A { void M() { System.Console.WriteLine(2); } }"; var source3 = "class A { void M() { System.Console.WriteLine(3); } }"; var compilationA = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "A"); var compilationB = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "B"); var (peImageA, pdbImageA) = compilationA.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataA = ModuleMetadata.CreateFromImage(peImageA); var moduleFileA = Temp.CreateFile("A.dll").WriteAllBytes(peImageA); var pdbFileA = dir.CreateFile("A.pdb").WriteAllBytes(pdbImageA); var moduleIdA = moduleMetadataA.GetModuleVersionId(); var (peImageB, pdbImageB) = compilationB.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataB = ModuleMetadata.CreateFromImage(peImageB); var moduleFileB = dir.CreateFile("B.dll").WriteAllBytes(peImageB); var pdbFileB = dir.CreateFile("B.pdb").WriteAllBytes(pdbImageB); var moduleIdB = moduleMetadataB.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var documentA) = AddDefaultTestProject(solution, source1); var projectA = documentA.Project; var projectB = solution.AddProject("B", "A", "C#").AddMetadataReferences(projectA.MetadataReferences).AddDocument("DocB", source1, filePath: "DocB.cs").Project; solution = projectB.Solution; _mockCompilationOutputsProvider = project => (project.Id == projectA.Id) ? new CompilationOutputFiles(moduleFileA.Path, pdbFileA.Path) : (project.Id == projectB.Id) ? new CompilationOutputFiles(moduleFileB.Path, pdbFileB.Path) : throw ExceptionUtilities.UnexpectedValue(project); // only module A is loaded LoadLibraryToDebuggee(moduleIdA); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // // First update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); var deltaA = updates.Updates.Single(d => d.Module == moduleIdA); var deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); var baselineA0 = newBaselineA1.GetInitialEmitBaseline(); var baselineB0 = newBaselineB1.GetInitialEmitBaseline(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(4, readers.Length); Assert.False(readers.Any(r => r is null)); Assert.Equal(moduleIdA, newBaselineA1.OriginalMetadata.GetModuleVersionId()); Assert.Equal(moduleIdB, newBaselineB1.OriginalMetadata.GetModuleVersionId()); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // verify that baseline is added for both modules: Assert.Same(newBaselineA1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); EnterBreakState(debuggingSession); // // Second update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); deltaA = updates.Updates.Single(d => d.Module == moduleIdA); deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); Assert.NotSame(newBaselineA1, newBaselineA2); Assert.NotSame(newBaselineB1, newBaselineB2); Assert.Same(baselineA0, newBaselineA2.GetInitialEmitBaseline()); Assert.Same(baselineB0, newBaselineB2.GetInitialEmitBaseline()); Assert.Same(baselineA0.OriginalMetadata, newBaselineA2.OriginalMetadata); Assert.Same(baselineB0.OriginalMetadata, newBaselineB2.OriginalMetadata); // no new module readers: var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // module readers tracked: baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); // verify that baseline is updated for both modules: Assert.Same(newBaselineA2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); EndDebuggingSession(debuggingSession); // open deferred module readers should be dispose when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task BreakMode_ValidSignificantChange_BaselineCreationFailed_NoStream() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => null, OpenAssemblyStreamImpl = () => null, }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document1.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-pdb", new FileNotFoundException().Message)}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); } [Fact] public async Task BreakMode_ValidSignificantChange_BaselineCreationFailed_AssemblyReadError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll, assemblyName: "lib"); var pdbStream = new MemoryStream(); var peImage = compilationV1.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), pdbStream: pdbStream); pdbStream.Position = 0; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => pdbStream, OpenAssemblyStreamImpl = () => throw new IOException("*message*"), }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-assembly", "*message*")}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } [Fact] public async Task ActiveStatements() { var sourceV1 = "class C { void F() { G(1); } void G(int a) => System.Console.WriteLine(1); }"; var sourceV2 = "class C { int x; void F() { G(2); G(1); } void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1);"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var activeSpan21 = GetSpan(sourceV2, "G(2); G(1);"); var activeSpan22 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var adjustedActiveSpan1 = GetSpan(sourceV2, "G(2);"); var adjustedActiveSpan2 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var documentId = document1.Id; var documentPath = document1.FilePath; var sourceTextV1 = document1.GetTextSynchronously(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var activeLineSpan21 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan21); var activeLineSpan22 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan22); var adjustedActiveLineSpan1 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan1); var adjustedActiveLineSpan2 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // default if not called in a break state Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None)).IsDefault); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentPath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentPath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var activeStatementSpan11 = new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan12 = new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); AssertEx.Equal(new[] { activeStatementSpan11, activeStatementSpan12 }, baseSpans.Single()); var trackedActiveSpans1 = ImmutableArray.Create(activeStatementSpan11, activeStatementSpan12); var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document1, (_, _, _) => new(trackedActiveSpans1), CancellationToken.None); AssertEx.Equal(trackedActiveSpans1, currentSpans); Assert.Equal(activeLineSpan11, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction1, CancellationToken.None)); Assert.Equal(activeLineSpan12, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction2, CancellationToken.None)); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // tracking span update triggered by the edit: var activeStatementSpan21 = new ActiveStatementSpan(0, activeLineSpan21, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan22 = new ActiveStatementSpan(1, activeLineSpan22, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var trackedActiveSpans2 = ImmutableArray.Create(activeStatementSpan21, activeStatementSpan22); currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => new(trackedActiveSpans2), CancellationToken.None); AssertEx.Equal(new[] { adjustedActiveLineSpan1, adjustedActiveLineSpan2 }, currentSpans.Select(s => s.LineSpan)); Assert.Equal(adjustedActiveLineSpan1, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction1, CancellationToken.None)); Assert.Equal(adjustedActiveLineSpan2, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction2, CancellationToken.None)); } [Theory] [CombinatorialData] public async Task ActiveStatements_SyntaxErrorOrOutOfSyncDocument(bool isOutOfSync) { var sourceV1 = "class C { void F() => G(1); void G(int a) => System.Console.WriteLine(1); }"; // syntax error (missing ';') unless testing out-of-sync document var sourceV2 = isOutOfSync ? "class C { int x; void F() => G(1); void G(int a) => System.Console.WriteLine(2); }" : "class C { int x void F() => G(1); void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1)"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var documentId = document1.Id; var documentFilePath = document1.FilePath; var sourceTextV1 = await document1.GetTextAsync(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var debuggingSession = await StartDebuggingSessionAsync( service, solution, isOutOfSync ? CommittedSolution.DocumentState.OutOfSync : CommittedSolution.DocumentState.MatchesBuildOutput); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentFilePath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentFilePath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var baseSpans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null), new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null) }, baseSpans); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // no adjustments made due to syntax error or out-of-sync document: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), CancellationToken.None); AssertEx.Equal(new[] { activeLineSpan11, activeLineSpan12 }, currentSpans.Select(s => s.LineSpan)); var currentSpan1 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction1, CancellationToken.None); var currentSpan2 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction2, CancellationToken.None); if (isOutOfSync) { Assert.Equal(baseSpans[0].LineSpan, currentSpan1.Value); Assert.Equal(baseSpans[1].LineSpan, currentSpan2.Value); } else { Assert.Null(currentSpan1); Assert.Null(currentSpan2); } } [Fact] public async Task ActiveStatements_ForeignDocument() { var composition = FeaturesTestCompositions.Features.AddParts(typeof(DummyLanguageService)); using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(Guid.Empty, token: 0x06000001, version: 1), ilOffset: 0), documentName: document.Name, sourceSpan: new SourceSpan(0, 1, 0, 2), ActiveStatementFlags.IsNonLeafFrame)); EnterBreakState(debuggingSession, activeStatements); // active statements are not tracked in non-Roslyn projects: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None); Assert.Empty(currentSpans); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); Assert.Empty(baseSpans.Single()); } [Fact, WorkItem(24320, "https://github.com/dotnet/roslyn/issues/24320")] public async Task ActiveStatements_LinkedDocuments() { var markedSources = new[] { @"class Test1 { static void Main() => <AS:2>Project2::Test1.F();</AS:2> static void F() => <AS:1>Project4::Test2.M();</AS:1> }", @"class Test2 { static void M() => <AS:0>Console.WriteLine();</AS:0> }" }; var module1 = Guid.NewGuid(); var module2 = Guid.NewGuid(); var module4 = Guid.NewGuid(); var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 1 }, modules: new[] { module4, module2, module1 }); // Project1: Test1.cs, Test2.cs // Project2: Test1.cs (link from P1) // Project3: Test1.cs (link from P1) // Project4: Test2.cs (link from P1) using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var documents = solution.Projects.Single().Documents; var doc1 = documents.First(); var doc2 = documents.Skip(1).First(); var text1 = await doc1.GetTextAsync(); var text2 = await doc2.GetTextAsync(); DocumentId AddProjectAndLinkDocument(string projectName, Document doc, SourceText text) { var p = solution.AddProject(projectName, projectName, "C#"); var linkedDocId = DocumentId.CreateNewId(p.Id, projectName + "->" + doc.Name); solution = p.Solution.AddDocument(linkedDocId, doc.Name, text, filePath: doc.FilePath); return linkedDocId; } var docId3 = AddProjectAndLinkDocument("Project2", doc1, text1); var docId4 = AddProjectAndLinkDocument("Project3", doc1, text1); var docId5 = AddProjectAndLinkDocument("Project4", doc2, text2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, debugInfos); // Base Active Statements var baseActiveStatementsMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); var documentMap = baseActiveStatementsMap.DocumentPathMap; Assert.Equal(2, documentMap.Count); AssertEx.Equal(new[] { $"2: {doc1.FilePath}: (2,32)-(2,52) flags=[MethodUpToDate, IsNonLeafFrame]", $"1: {doc1.FilePath}: (3,29)-(3,49) flags=[MethodUpToDate, IsNonLeafFrame]" }, documentMap[doc1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"0: {doc2.FilePath}: (0,39)-(0,59) flags=[IsLeafFrame, MethodUpToDate]", }, documentMap[doc2.FilePath].Select(InspectActiveStatement)); Assert.Equal(3, baseActiveStatementsMap.InstructionMap.Count); var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module4, s.InstructionId.Method.Module); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(module2, s.InstructionId.Method.Module); s = statements[2]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module1, s.InstructionId.Method.Module); var spans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(doc1.Id, doc2.Id, docId3, docId4, docId5), CancellationToken.None); AssertEx.Equal(new[] { "(2,32)-(2,52), (3,29)-(3,49)", // test1.cs "(0,39)-(0,59)", // test2.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(0,39)-(0,59)" // link test2.cs }, spans.Select(docSpans => string.Join(", ", docSpans.Select(span => span.LineSpan)))); } [Fact] public async Task ActiveStatements_OutOfSyncDocuments() { var markedSource1 = @"class C { static void M() { try { } catch (Exception e) { <AS:0>M();</AS:0> } } }"; var source2 = @"class C { static void M() { try { } catch (Exception e) { M(); } } }"; var markedSources = new[] { markedSource1 }; var thread1 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0 leaf) var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1 }, ilOffsets: new[] { 1 }, flags: new[] { ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var project = solution.Projects.Single(); var document = project.Documents.Single(); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.OutOfSync); EnterBreakState(debuggingSession, debugInfos); // update document to test a changed solution solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); document = solution.GetDocument(document.Id); var baseActiveStatementMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements - available in out-of-sync documents, as they reflect the state of the debuggee and not the base document content Assert.Single(baseActiveStatementMap.DocumentPathMap); AssertEx.Equal(new[] { $"0: {document.FilePath}: (9,18)-(9,22) flags=[IsLeafFrame, MethodUpToDate]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(1, baseActiveStatementMap.InstructionMap.Count); var activeStatement1 = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).Single(); Assert.Equal(0x06000001, activeStatement1.InstructionId.Method.Token); Assert.Equal(document.FilePath, activeStatement1.FilePath); Assert.True(activeStatement1.IsLeaf); // Active statement reported as unchanged as the containing document is out-of-sync: var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(9,18)-(9,22)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); // Whether or not an active statement is in an exception region is unknown if the document is out-of-sync: Assert.Null(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); // Document got synchronized: debuggingSession.LastCommittedSolution.Test_SetDocumentState(document.Id, CommittedSolution.DocumentState.MatchesBuildOutput); // New location of the active statement reported: baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(10,12)-(10,16)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); Assert.True(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); } [Fact] public async Task ActiveStatements_SourceGeneratedDocuments_LineDirectives() { var markedSource1 = @" /* GENERATE: class C { void F() { #line 1 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var markedSource2 = @" /* GENERATE: class C { void F() { #line 2 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var source1 = ActiveStatementsDescription.ClearTags(markedSource1); var source2 = ActiveStatementsDescription.ClearTags(markedSource2); var additionalFileSourceV1 = @" xxxxxxxxxxxxxxxxx "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator, additionalFileText: additionalFileSourceV1); var generatedDocument1 = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync().ConfigureAwait(false)).Single(); var moduleId = EmitLibrary(source1, generator: generator, additionalFileText: additionalFileSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { GetGeneratedCodeFromMarkedSource(markedSource1) }, filePaths: new[] { generatedDocument1.FilePath }, modules: new[] { moduleId }, methodRowIds: new[] { 1 }, methodVersions: new[] { 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame })); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); AssertEx.Equal(new[] { "a.razor: [0 -> 1]" }, delta.SequencePoints.Inspect()); EndDebuggingSession(debuggingSession); } /// <summary> /// Scenario: /// F5 a program that has function F that calls G. G has a long-running loop, which starts executing. /// The user makes following operations: /// 1) Break, edit F from version 1 to version 2, continue (change is applied), G is still running in its loop /// Function remapping is produced for F v1 -> F v2. /// 2) Hot-reload edit F (without breaking) to version 3. /// Function remapping is produced for F v2 -> F v3 based on the last set of active statements calculated for F v2. /// Assume that the execution did not progress since the last resume. /// These active statements will likely not match the actual runtime active statements, /// however F v2 will never be remapped since it was hot-reloaded and not EnC'd. /// This remapping is needed for mapping from F v1 to F v3. /// 3) Break. Update F to v4. /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakStateRemappingFollowedUpByRunStateUpdate() { var markedSourceV1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { /*insert1[1]*/B();/*insert2[5]*/B();/*insert3[10]*/B(); <AS:1>G();</AS:1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var markedSourceV4 = Update(markedSourceV3, marker: "3"); var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSourceV1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSourceV1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // EnC update F v1 -> v2 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); ExitBreakState(); // Hot Reload update F v2 -> v3 solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV3), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); // EnC update F v3 -> v4 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, // matches F v1 modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F - not up-to-date anymore })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV4), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // TODO: https://github.com/dotnet/roslyn/issues/52100 // this is incorrect. correct value is: 0x06000003 v1 | AS (9,14)-(9,18) δ=16 AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=5" }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); ExitBreakState(); } /// <summary> /// Scenario: /// - F5 /// - edit, but not apply the edits /// - break /// </summary> [Fact] public async Task BreakInPresenceOfUnappliedChanges() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); <AS:1>G();</AS:1> } }"; var markedSource3 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); B(); <AS:1>G();</AS:1> } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Update to snapshot 2, but don't apply solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); // EnC update F v2 -> v3 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF1 = new LinePositionSpan(new LinePosition(8, 14), new LinePosition(8, 18)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span.Value); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource3), Encoding.UTF8)); // check that the active statement is mapped correctly to snapshot v3: var expectedSpanG2 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF2 = new LinePositionSpan(new LinePosition(9, 14), new LinePosition(9, 18)); span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF2, span); spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); // no rude edits: var document1 = solution.GetDocument(documentId); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (7,14)-(7,18) δ=2", }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); ExitBreakState(); } /// <summary> /// Scenario: /// - F5 /// - edit and apply edit that deletes non-leaf active statement /// - break /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakAfterRunModeChangeDeletesNonLeafActiveStatement() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Apply update: F v1 -> v2. solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // Break EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanF1 = new LinePositionSpan(new LinePosition(7, 14), new LinePosition(7, 18)); var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null), // TODO: https://github.com/dotnet/roslyn/issues/52100 // This is incorrect: the active statement shouldn't be reported since it has been deleted. // We need the debugger to mark the method version as replaced by run-mode update. new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null) }, spans); ExitBreakState(); } [Fact] public async Task MultiSession() { var source1 = "class C { void M() { System.Console.WriteLine(); } }"; var source3 = "class C { void M() { WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var tasks = Enumerable.Range(0, 10).Select(async i => { var sessionId = await encService.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: true, reportDiagnostics: true, CancellationToken.None); var solution1 = solution.WithDocumentText(documentIdA, SourceText.From("class C { void M() { System.Console.WriteLine(" + i + "); } }", Encoding.UTF8)); var result1 = await encService.EmitSolutionUpdateAsync(sessionId, solution1, s_noActiveSpans, CancellationToken.None); Assert.Empty(result1.Diagnostics); Assert.Equal(1, result1.ModuleUpdates.Updates.Length); var solution2 = solution1.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); var result2 = await encService.EmitSolutionUpdateAsync(sessionId, solution2, s_noActiveSpans, CancellationToken.None); Assert.Equal("CS0103", result2.Diagnostics.Single().Diagnostics.Single().Id); Assert.Empty(result2.ModuleUpdates.Updates); encService.EndDebuggingSession(sessionId, out var _); }); await Task.WhenAll(tasks); Assert.Empty(encService.GetTestAccessor().GetActiveDebuggingSessions()); } [Fact] public async Task WatchHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new WatchHotReloadService(workspace.Services, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition")); await hotReload.StartSessionAsync(solution, CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); AssertEx.Equal(new[] { 0x02000002 }, result.updates[0].UpdatedTypes); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); hotReload.EndSession(); } [Fact] public async Task UnitTestingHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new UnitTestingHotReloadService(workspace.Services); await hotReload.StartSessionAsync(solution, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition"), CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); hotReload.EndSession(); } [Fact] public void ParseCapabilities() { var capabilities = ImmutableArray.Create("Baseline"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.True(service.HasFlag(EditAndContinueCapabilities.Baseline)); Assert.False(service.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)); } [Fact] public void ParseCapabilities_CaseSensitive() { var capabilities = ImmutableArray.Create("BaseLine"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.False(service.HasFlag(EditAndContinueCapabilities.Baseline)); } [Fact] public void ParseCapabilities_IgnoreInvalid() { var capabilities = ImmutableArray.Create("Baseline", "Invalid", "NewTypeDefinition"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.True(service.HasFlag(EditAndContinueCapabilities.Baseline)); Assert.True(service.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)); } [Fact] public void ParseCapabilities_IgnoreInvalidNumeric() { var capabilities = ImmutableArray.Create("Baseline", "90", "NewTypeDefinition"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.True(service.HasFlag(EditAndContinueCapabilities.Baseline)); Assert.True(service.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)); } [Fact] public void ParseCapabilities_AllCapabilitiesParsed() { foreach (var name in Enum.GetNames(typeof(EditAndContinueCapabilities))) { var capabilities = ImmutableArray.Create(name); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); var flag = (EditAndContinueCapabilities)Enum.Parse(typeof(EditAndContinueCapabilities), name); Assert.True(service.HasFlag(flag), $"Capability '{name}' was not parsed correctly, so it's impossible for a runtime to enable it!"); } } } }
1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/Features/Core/Portable/ExternalAccess/Watch/Api/WatchHotReloadService.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.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.Watch.Api { internal sealed class WatchHotReloadService { private sealed class DebuggerService : IManagedEditAndContinueDebuggerService { private readonly ImmutableArray<string> _capabilities; public DebuggerService(ImmutableArray<string> capabilities) => _capabilities = capabilities; public Task<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(CancellationToken cancellationToken) => Task.FromResult(ImmutableArray<ManagedActiveStatementDebugInfo>.Empty); public Task<ManagedEditAndContinueAvailability> GetAvailabilityAsync(Guid module, CancellationToken cancellationToken) => Task.FromResult(new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Available)); public Task<ImmutableArray<string>> GetCapabilitiesAsync(CancellationToken cancellationToken) => Task.FromResult(_capabilities); public Task PrepareModuleForUpdateAsync(Guid module, CancellationToken cancellationToken) => Task.CompletedTask; } public readonly struct Update { public readonly Guid ModuleId; public readonly ImmutableArray<byte> ILDelta; public readonly ImmutableArray<byte> MetadataDelta; public readonly ImmutableArray<byte> PdbDelta; public readonly ImmutableArray<int> UpdatedTypes; public Update(Guid moduleId, ImmutableArray<byte> ilDelta, ImmutableArray<byte> metadataDelta, ImmutableArray<byte> pdbDelta, ImmutableArray<int> updatedTypes) { ModuleId = moduleId; ILDelta = ilDelta; MetadataDelta = metadataDelta; PdbDelta = pdbDelta; UpdatedTypes = updatedTypes; } } private static readonly ActiveStatementSpanProvider s_solutionActiveStatementSpanProvider = (_, _, _) => ValueTaskFactory.FromResult(ImmutableArray<ActiveStatementSpan>.Empty); private readonly IEditAndContinueWorkspaceService _encService; private DebuggingSessionId _sessionId; private readonly ImmutableArray<string> _capabilities; public WatchHotReloadService(HostWorkspaceServices services, ImmutableArray<string> capabilities) => (_encService, _capabilities) = (services.GetRequiredService<IEditAndContinueWorkspaceService>(), capabilities); /// <summary> /// Starts the watcher. /// </summary> /// <param name="solution">Solution that represents sources that match the built binaries on disk.</param> /// <param name="cancellationToken">Cancellation token.</param> public async Task StartSessionAsync(Solution solution, CancellationToken cancellationToken) { var newSessionId = await _encService.StartDebuggingSessionAsync( solution, new DebuggerService(_capabilities), captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: true, reportDiagnostics: false, cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(_sessionId == default, "Session already started"); _sessionId = newSessionId; } /// <summary> /// Emits updates for all projects that differ between the given <paramref name="solution"/> snapshot and the one given to the previous successful call or /// the one passed to <see cref="StartSessionAsync(Solution, CancellationToken)"/> for the first invocation. /// </summary> /// <param name="solution">Solution snapshot.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns> /// Updates (one for each changed project) and Rude Edit diagnostics. Does not include syntax or semantic diagnostics. /// </returns> public async Task<(ImmutableArray<Update> updates, ImmutableArray<Diagnostic> diagnostics)> EmitSolutionUpdateAsync(Solution solution, CancellationToken cancellationToken) { var sessionId = _sessionId; Contract.ThrowIfFalse(sessionId != default, "Session has not started"); var results = await _encService.EmitSolutionUpdateAsync(sessionId, solution, s_solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (results.ModuleUpdates.Status == ManagedModuleUpdateStatus.Ready) { _encService.CommitSolutionUpdate(sessionId, out _); } var updates = results.ModuleUpdates.Updates.SelectAsArray( update => new Update(update.Module, update.ILDelta, update.MetadataDelta, update.PdbDelta, update.UpdatedTypes)); var diagnostics = await results.GetAllDiagnosticsAsync(solution, cancellationToken).ConfigureAwait(false); return (updates, diagnostics); } public void EndSession() { Contract.ThrowIfFalse(_sessionId != default, "Session has not started"); _encService.EndDebuggingSession(_sessionId, out _); } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly WatchHotReloadService _instance; internal TestAccessor(WatchHotReloadService instance) => _instance = instance; public DebuggingSessionId SessionId => _instance._sessionId; } } }
// Licensed to the .NET Foundation under one or more 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.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.Watch.Api { internal sealed class WatchHotReloadService { private sealed class DebuggerService : IManagedEditAndContinueDebuggerService { private readonly ImmutableArray<string> _capabilities; public DebuggerService(ImmutableArray<string> capabilities) => _capabilities = capabilities; public Task<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(CancellationToken cancellationToken) => Task.FromResult(ImmutableArray<ManagedActiveStatementDebugInfo>.Empty); public Task<ManagedEditAndContinueAvailability> GetAvailabilityAsync(Guid module, CancellationToken cancellationToken) => Task.FromResult(new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Available)); public Task<ImmutableArray<string>> GetCapabilitiesAsync(CancellationToken cancellationToken) => Task.FromResult(_capabilities); public Task PrepareModuleForUpdateAsync(Guid module, CancellationToken cancellationToken) => Task.CompletedTask; } public readonly struct Update { public readonly Guid ModuleId; public readonly ImmutableArray<byte> ILDelta; public readonly ImmutableArray<byte> MetadataDelta; public readonly ImmutableArray<byte> PdbDelta; public readonly ImmutableArray<int> UpdatedTypes; public Update(Guid moduleId, ImmutableArray<byte> ilDelta, ImmutableArray<byte> metadataDelta, ImmutableArray<byte> pdbDelta, ImmutableArray<int> updatedTypes) { ModuleId = moduleId; ILDelta = ilDelta; MetadataDelta = metadataDelta; PdbDelta = pdbDelta; UpdatedTypes = updatedTypes; } } private static readonly ActiveStatementSpanProvider s_solutionActiveStatementSpanProvider = (_, _, _) => ValueTaskFactory.FromResult(ImmutableArray<ActiveStatementSpan>.Empty); private readonly IEditAndContinueWorkspaceService _encService; private DebuggingSessionId _sessionId; private readonly ImmutableArray<string> _capabilities; public WatchHotReloadService(HostWorkspaceServices services, ImmutableArray<string> capabilities) => (_encService, _capabilities) = (services.GetRequiredService<IEditAndContinueWorkspaceService>(), capabilities); /// <summary> /// Starts the watcher. /// </summary> /// <param name="solution">Solution that represents sources that match the built binaries on disk.</param> /// <param name="cancellationToken">Cancellation token.</param> public async Task StartSessionAsync(Solution solution, CancellationToken cancellationToken) { var newSessionId = await _encService.StartDebuggingSessionAsync( solution, new DebuggerService(_capabilities), captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: true, reportDiagnostics: false, cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(_sessionId == default, "Session already started"); _sessionId = newSessionId; } /// <summary> /// Emits updates for all projects that differ between the given <paramref name="solution"/> snapshot and the one given to the previous successful call or /// the one passed to <see cref="StartSessionAsync(Solution, CancellationToken)"/> for the first invocation. /// </summary> /// <param name="solution">Solution snapshot.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns> /// Updates (one for each changed project) and Rude Edit diagnostics. Does not include syntax or semantic diagnostics. /// </returns> public async Task<(ImmutableArray<Update> updates, ImmutableArray<Diagnostic> diagnostics)> EmitSolutionUpdateAsync(Solution solution, CancellationToken cancellationToken) { var sessionId = _sessionId; Contract.ThrowIfFalse(sessionId != default, "Session has not started"); var results = await _encService.EmitSolutionUpdateAsync(sessionId, solution, s_solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (results.ModuleUpdates.Status == ManagedModuleUpdateStatus.Ready) { _encService.CommitSolutionUpdate(sessionId, out _); } var updates = results.ModuleUpdates.Updates.SelectAsArray( update => new Update(update.Module, update.ILDelta, update.MetadataDelta, update.PdbDelta, update.UpdatedTypes)); var diagnostics = await results.GetAllDiagnosticsAsync(solution, cancellationToken).ConfigureAwait(false); return (updates, diagnostics); } public void EndSession() { Contract.ThrowIfFalse(_sessionId != default, "Session has not started"); _encService.EndDebuggingSession(_sessionId, out _); } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly WatchHotReloadService _instance; internal TestAccessor(WatchHotReloadService instance) => _instance = instance; public DebuggingSessionId SessionId => _instance._sessionId; } } }
1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/Workspaces/Core/Portable/Log/EtwLogger.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics.Tracing; using System.Threading; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Internal.Log { /// <summary> /// A logger that publishes events to ETW using an EventSource. /// </summary> internal sealed class EtwLogger : ILogger { private readonly Lazy<Func<FunctionId, bool>> _loggingChecker; // Due to ETW specifics, RoslynEventSource.Instance needs to be initialized during EtwLogger construction // so that we can enable the listeners synchronously before any events are logged. private readonly RoslynEventSource _source = RoslynEventSource.Instance; public EtwLogger(IGlobalOptionService optionService) => _loggingChecker = new Lazy<Func<FunctionId, bool>>(() => Logger.GetLoggingChecker(optionService)); public EtwLogger(Func<FunctionId, bool> loggingChecker) => _loggingChecker = new Lazy<Func<FunctionId, bool>>(() => loggingChecker); public bool IsEnabled(FunctionId functionId) => _source.IsEnabled() && _loggingChecker.Value(functionId); public void Log(FunctionId functionId, LogMessage logMessage) => _source.Log(GetMessage(logMessage), functionId); public void LogBlockStart(FunctionId functionId, LogMessage logMessage, int uniquePairId, CancellationToken cancellationToken) => _source.BlockStart(GetMessage(logMessage), functionId, uniquePairId); public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { _source.BlockCanceled(functionId, delta, uniquePairId); } else { _source.BlockStop(functionId, delta, uniquePairId); } } private bool IsVerbose() { // "-1" makes this to work with any keyword return _source.IsEnabled(EventLevel.Verbose, (EventKeywords)(-1)); } private string GetMessage(LogMessage logMessage) => IsVerbose() ? logMessage.GetMessage() : string.Empty; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics.Tracing; using System.Threading; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Internal.Log { /// <summary> /// A logger that publishes events to ETW using an EventSource. /// </summary> internal sealed class EtwLogger : ILogger { private readonly Lazy<Func<FunctionId, bool>> _loggingChecker; // Due to ETW specifics, RoslynEventSource.Instance needs to be initialized during EtwLogger construction // so that we can enable the listeners synchronously before any events are logged. private readonly RoslynEventSource _source = RoslynEventSource.Instance; public EtwLogger(IGlobalOptionService optionService) => _loggingChecker = new Lazy<Func<FunctionId, bool>>(() => Logger.GetLoggingChecker(optionService)); public EtwLogger(Func<FunctionId, bool> loggingChecker) => _loggingChecker = new Lazy<Func<FunctionId, bool>>(() => loggingChecker); public bool IsEnabled(FunctionId functionId) => _source.IsEnabled() && _loggingChecker.Value(functionId); public void Log(FunctionId functionId, LogMessage logMessage) => _source.Log(GetMessage(logMessage), functionId); public void LogBlockStart(FunctionId functionId, LogMessage logMessage, int uniquePairId, CancellationToken cancellationToken) => _source.BlockStart(GetMessage(logMessage), functionId, uniquePairId); public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { _source.BlockCanceled(functionId, delta, uniquePairId); } else { _source.BlockStop(functionId, delta, uniquePairId); } } private bool IsVerbose() { // "-1" makes this to work with any keyword return _source.IsEnabled(EventLevel.Verbose, (EventKeywords)(-1)); } private string GetMessage(LogMessage logMessage) => IsVerbose() ? logMessage.GetMessage() : string.Empty; } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/EditorFeatures/CSharpTest/CodeActions/ConvertLinq/ConvertForEachToLinqQueryTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.ConvertLinq { public class ConvertForEachToLinqQueryTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery.CSharpConvertForEachToLinqQueryProvider(); #region Query Expressions [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryForForWhere() { var source = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; [|foreach (var x1 in c1) { foreach (var x2 in c2) { if (object.Equals(x1, x2 / 10)) { yield return x1 + x2; } } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; return from x1 in c1 from x2 in c2 where object.Equals(x1, x2 / 10) select x1 + x2; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; return c1.SelectMany(x1 => c2.Where(x2 => object.Equals(x1, x2 / 10)).Select(x2 => x1 + x2)); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryWithEscapedSymbols() { var source = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; [|foreach (var @object in c1) { foreach (var x2 in c2) { yield return @object + x2; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; return from @object in c1 from x2 in c2 select @object + x2; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; return c1.SelectMany(@object => c2.Select(x2 => @object + x2)); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryForVarForWhere() { var source = @" using System.Linq; class C { IEnumerable<int> M() { [|foreach (var num in new int[] { 1, 2 }) { var n1 = num + 1; foreach (var a in new int[] { 5, 6 }) { foreach (var x1 in new int[] { 3, 4 }) { if (object.Equals(num, x1)) { foreach (var x2 in new int[] { 7, 8 }) { if (object.Equals(num, x2)) { var n2 = x2 - 1; yield return n2 + n1; } } } } }|] } } }"; var queryOutput = @" using System.Linq; class C { IEnumerable<int> M() { return from num in new int[] { 1, 2 } let n1 = num + 1 from a in new int[] { 5, 6 } from x1 in new int[] { 3, 4 } where object.Equals(num, x1) from x2 in new int[] { 7, 8 } where object.Equals(num, x2) let n2 = x2 - 1 select n2 + n1; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); // No linq refactoring offered due to variable declaration within the outermost foreach. await TestActionCountAsync(source, count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryForVarForWhere_02() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { [|foreach (var num in new int[] { 1, 2 }) { foreach (var a in new int[] { 5, 6 }) { foreach (var x1 in new int[] { 3, 4 }) { if (object.Equals(num, x1)) { foreach (var x2 in new int[] { 7, 8 }) { if (object.Equals(num, x2)) { var n1 = num + 1; var n2 = x2 - 1; yield return n2 + n1; } } } } }|] } } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { return from num in new int[] { 1, 2 } from a in new int[] { 5, 6 } from x1 in new int[] { 3, 4 } where object.Equals(num, x1) from x2 in new int[] { 7, 8 } where object.Equals(num, x2) let n1 = num + 1 let n2 = x2 - 1 select n2 + n1; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { foreach (var (num, x2) in (new int[] { 1, 2 }).SelectMany(num => (new int[] { 5, 6 }).SelectMany(a => (new int[] { 3, 4 }).Where(x1 => object.Equals(num, x1)).SelectMany(x1 => (new int[] { 7, 8 }).Where(x2 => object.Equals(num, x2)).Select(x2 => (num, x2)))))) { var n1 = num + 1; var n2 = x2 - 1; yield return n2 + n1; } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryForVarForWhere_03() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { [|foreach (var num in new int[] { 1, 2 }) { foreach (var a in new int[] { 5, 6 }) { foreach (var x1 in new int[] { 3, 4 }) { var n1 = num + 1; if (object.Equals(num, x1)) { foreach (var x2 in new int[] { 7, 8 }) { if (object.Equals(num, x2)) { var n2 = x2 - 1; yield return n2 + n1; } } } } }|] } } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { return from num in new int[] { 1, 2 } from a in new int[] { 5, 6 } from x1 in new int[] { 3, 4 } let n1 = num + 1 where object.Equals(num, x1) from x2 in new int[] { 7, 8 } where object.Equals(num, x2) let n2 = x2 - 1 select n2 + n1; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { foreach (var (num, x1) in (new int[] { 1, 2 }).SelectMany(num => (new int[] { 5, 6 }).SelectMany(a => (new int[] { 3, 4 }).Select(x1 => (num, x1))))) { var n1 = num + 1; if (object.Equals(num, x1)) { foreach (var x2 in new int[] { 7, 8 }) { if (object.Equals(num, x2)) { var n2 = x2 - 1; yield return n2 + n1; } } } } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryLet() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { void M() { List<int> c1 = new List<int>{ 1, 2, 3 }; List<int> r1 = new List<int>(); [|foreach (int x in c1) { var g = x * 10; var z = g + x*100; var a = 5 + z; r1.Add(x + z - a); }|] } }"; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class Query { void M() { List<int> c1 = new List<int>{ 1, 2, 3 }; List<int> r1 = (from int x in c1 let g = x * 10 let z = g + x * 100 let a = 5 + z select x + z - a).ToList(); } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); // No linq invocation refactoring offered due to variable declaration(s) in topmost foreach. await TestActionCountAsync(source, count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryEmptyDeclarations() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { void M() { [|foreach (int x in new[] {1,2}) { int a = 3, b, c = 1; if (x > c) { b = 0; Console.Write(a + x + b); } }|] } }"; await TestMissingInRegularAndScriptAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryWhereClause() { var source = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; [|foreach (var x in nums) { if (x > 2) { yield return x; } }|] } }"; var queryOutput = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; return from x in nums where x > 2 select x; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; return nums.Where(x => x > 2); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryOverQueries() { var source = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; [|foreach (var y in from x in nums select x) { foreach (var z in from x in nums select x) { yield return y; } }|] } }"; var queryOutput = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; return from y in from x in nums select x from z in from x in nums select x select y; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; return (from x in nums select x).SelectMany(y => (from x in nums select x).Select(z => y)); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryNoVariablesUsed() { var source = @" using System; using System.Linq; class C { void M() { [|foreach (var a in new[] { 1 }) { foreach (var b in new[] { 2 }) { System.Console.Write(0); } }|] } }"; var queryOutput = @" using System; using System.Linq; class C { void M() { foreach (var _ in from a in new[] { 1 } from b in new[] { 2 } select new { }) { System.Console.Write(0); } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { void M() { foreach (var _ in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => new { }))) { System.Console.Write(0); } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryNoBlock() { var source = @" using System; using System.Linq; class C { void M() { [|foreach (var a in new[] { 1 }) foreach (var b in new[] { 2 }) System.Console.Write(a);|] } }"; var queryOutput = @" using System; using System.Linq; class C { void M() { foreach (var a in from a in new[] { 1 } from b in new[] { 2 } select a) { System.Console.Write(a); } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { void M() { foreach (var a in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => a))) { System.Console.Write(a); } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QuerySelectExpression() { var source = @" using System; using System.Linq; class C { void M() { [|foreach (var a in new[] { 1 }) foreach (var b in new[] { 2 }) Console.Write(a + b);|] } }"; var queryOutput = @" using System; using System.Linq; class C { void M() { foreach (var (a, b) in from a in new[] { 1 } from b in new[] { 2 } select (a, b)) { Console.Write(a + b); } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { void M() { foreach (var (a, b) in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => (a, b)))) { Console.Write(a + b); } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QuerySelectMultipleExpressions() { var source = @" using System; using System.Linq; class C { void M() { [|foreach (var a in new[] { 1 }) foreach (var b in new[] { 2 }) { Console.Write(a + b); Console.Write(a * b); }|] } }"; var queryOutput = @" using System; using System.Linq; class C { void M() { foreach (var (a, b) in from a in new[] { 1 } from b in new[] { 2 } select (a, b)) { Console.Write(a + b); Console.Write(a * b); } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { void M() { foreach (var (a, b) in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => (a, b)))) { Console.Write(a + b); Console.Write(a * b); } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task EmptyBody() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in from int n1 in nums from int n2 in nums select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { }))) { } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task EmptyBodyNoBlock() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums); }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in from int n1 in nums from int n2 in nums select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { }))) { } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task AddUsingToExistingList() { var source = @" using System.Collections.Generic; class C { void M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums); }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in from int n1 in nums from int n2 in nums select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { }))) { } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task AddFirstUsing() { var source = @" class C { void M(int[] nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums); }|] } } "; var queryOutput = @"using System.Linq; class C { void M(int[] nums) { foreach (var _ in from int n1 in nums from int n2 in nums select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @"using System.Linq; class C { void M(int[] nums) { foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { }))) { } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task EmptyBodyDeclarationAsLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { var a = n1 + n2; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in from int n1 in nums from int n2 in nums let a = n1 + n2 select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var (n1, n2) in nums.SelectMany(n1 => nums.Select(n2 => (n1, n2)))) { var a = n1 + n2; } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task EmptyBodyMultipleDeclarationsAsLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { int a = n1 + n2, b = n1 * n2; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in from int n1 in nums from int n2 in nums let a = n1 + n2 let b = n1 * n2 select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var (n1, n2) in nums.SelectMany(n1 => nums.Select(n2 => (n1, n2)))) { int a = n1 + n2, b = n1 * n2; } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } #endregion #region Assignments, Declarations, Returns [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnInvocationAndYieldReturn() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { yield return N(n1); } }|] } int N(int n) => n; } "; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums from int n2 in nums select N(n1); } int N(int n) => n; } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return nums.SelectMany(n1 => nums.Select(n2 => N(n1))); } int N(int n) => n; } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task BlockBodiedProperty() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query1 { get { [|foreach (var x in _nums) { yield return x + 1; }|] } } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query1 { get { return from x in _nums select x + 1; } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query1 { get { return _nums.Select(x => x + 1); } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnIEnumerable() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums from int n2 in nums select n1; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return nums.SelectMany(n1 => nums.Select(n2 => n1)); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnIEnumerableWithYieldReturnAndLocalFunction() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<IEnumerable<int>> M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { yield return f(n1); } }|] yield break; IEnumerable<int> f(int a) { yield return a; } } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<IEnumerable<int>> M(IEnumerable<int> nums) { return from int n1 in nums from int n2 in nums select f(n1); IEnumerable<int> f(int a) { yield return a; } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<IEnumerable<int>> M(IEnumerable<int> nums) { return nums.SelectMany(n1 => nums.Select(n2 => f(n1))); IEnumerable<int> f(int a) { yield return a; } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnIEnumerablePartialMethod() { var source = @" using System.Collections.Generic; using System.Linq; partial class C { partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { partial IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } }|] yield break; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; partial class C { partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { partial IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums from int n2 in nums select n1; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; partial class C { partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { partial IEnumerable<int> M(IEnumerable<int> nums) { return nums.SelectMany(n1 => nums.Select(n2 => n1)); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnIEnumerableExtendedPartialMethod() { var source = @" using System.Collections.Generic; using System.Linq; partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } }|] yield break; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums from int n2 in nums select n1; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums) { return nums.SelectMany(n1 => nums.Select(n2 => n1)); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] [WorkItem(31784, "https://github.com/dotnet/roslyn/issues/31784")] public async Task QueryWhichRequiresSelectManyWithIdentityLambda() { var source = @" using System.Collections.Generic; class C { IEnumerable<int> M() { [|foreach (var x in new[] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 } }) { foreach (var y in x) { yield return y; } }|] } } "; var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { return (new[] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 } }).SelectMany(x => x); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } #endregion #region In foreach [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryInForEachWithSameVariableNameAndDifferentType() { var source = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class B : A { } class C { void M(IEnumerable<int> nums) { [|foreach (B a in nums) { foreach (A c in nums) { Console.Write(a.ToString()); } }|] } } "; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class B : A { } class C { void M(IEnumerable<int> nums) { foreach (var a in from B a in nums from A c in nums select a) { Console.Write(a.ToString()); } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class B : A { } class C { void M(IEnumerable<int> nums) { foreach (var a in nums.SelectMany(a => nums.Select(c => a))) { Console.Write(a.ToString()); } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryInForEachWithSameVariableNameAndSameType() { var source = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class C { void M(IEnumerable<int> nums) { [|foreach (A a in nums) { foreach (A c in nums) { Console.Write(a.ToString()); } }|] } } "; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class C { void M(IEnumerable<int> nums) { foreach (var a in from A a in nums from A c in nums select a) { Console.Write(a.ToString()); } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class C { void M(IEnumerable<int> nums) { foreach (var a in nums.SelectMany(a => nums.Select(c => a))) { Console.Write(a.ToString()); } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryInForEachWithConvertedType() { var source = @" using System; using System.Collections.Generic; static class Extensions { public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null; } class C { public static implicit operator int(C x) { throw null; } public static implicit operator C(int x) { throw null; } IEnumerable<C> Test() { [|foreach (var x in new[] { 1, 2, 3 }) { yield return x; }|] } } "; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; static class Extensions { public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null; } class C { public static implicit operator int(C x) { throw null; } public static implicit operator C(int x) { throw null; } IEnumerable<C> Test() { return from x in new[] { 1, 2, 3 } select x; } } "; await TestAsync(source, queryOutput, parseOptions: null); var linqInvocationOutput = @" using System; using System.Collections.Generic; using System.Linq; static class Extensions { public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null; } class C { public static implicit operator int(C x) { throw null; } public static implicit operator C(int x) { throw null; } IEnumerable<C> Test() { return new[] { 1, 2, 3 }; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task IQueryableConvertedToIEnumerableInReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums.AsQueryable()) { yield return n1; }|] yield break; } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums.AsQueryable() select n1; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return nums.AsQueryable(); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnIQueryableConvertedToIEnumerableInAssignment() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums.AsQueryable()) { yield return n1; }|] } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums.AsQueryable() select n1; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return nums.AsQueryable(); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } #endregion #region In ToList [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListLastDeclarationMerge() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list0 = new List<int>(), list = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list0 = new List<int>(); return (from int n1 in nums from int n2 in nums select n1).ToList(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list0 = new List<int>(); return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListParameterizedConstructor() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(nums); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(nums); list.AddRange(from int n1 in nums from int n2 in nums select n1); return list; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(nums); list.AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1))); return list; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListWithListInitializer() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>() { 1, 2, 3 }; [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>() { 1, 2, 3 }; list.AddRange(from int n1 in nums from int n2 in nums select n1); return list; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>() { 1, 2, 3 }; list.AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1))); return list; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListWithEmptyArgumentList() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int> { }; [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { return (from int n1 in nums from int n2 in nums select n1).ToList(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListNotLastDeclaration() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(), list1 = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(), list1 = new List<int>(); list.AddRange(from int n1 in nums from int n2 in nums select n1); return list; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(), list1 = new List<int>(); list.AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1))); return list; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListAssignToParameter() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums, List<int> list) { list = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums, List<int> list) { list = (from int n1 in nums from int n2 in nums select n1).ToList(); return list; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums, List<int> list) { list = (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); return list; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListToArrayElement() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { lists[0].Add(n1); } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { lists[0].AddRange(from int n1 in nums from int n2 in nums select n1); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { lists[0].AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1))); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListToNewArrayElement() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { lists[0] = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { lists[0].Add(n1); } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { lists[0] = (from int n1 in nums from int n2 in nums select n1).ToList(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { lists[0] = (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListHashSetNoConversion() { var source = @" using System.Collections.Generic; class C { void M(IEnumerable<int> nums) { var hashSet = new HashSet<int>(); [|foreach (int n1 in nums) { hashSet.Add(n1); }|] } } "; await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListMergeWithReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { var list = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { return (from int n1 in nums from int n2 in nums select n1).ToList(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListSeparateDeclarationAndAssignmentMergeWithReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list; list = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list; return (from int n1 in nums from int n2 in nums select n1).ToList(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list; return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListSeparateDeclarationAndAssignment() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { List<int> list; list = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list.Count; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { List<int> list; list = (from int n1 in nums from int n2 in nums select n1).ToList(); return list.Count; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { List<int> list; list = (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); return list.Count; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListTypeReplacement01() { var source = @" using System; using System.Linq; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C c3 = new C { 100, 200, 300 }; C r1 = new C(); [|foreach (int x in c1) { foreach (int y in c2) { foreach (int z in c3) { var g = x + y + z; if (x + y / 10 + z / 100 < 6) { r1.Add(g); } } } }|] Console.WriteLine(r1); } } "; var queryOutput = @" using System; using System.Linq; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C c3 = new C { 100, 200, 300 }; C r1 = (from int x in c1 from int y in c2 from int z in c3 let g = x + y + z where x + y / 10 + z / 100 < 6 select g).ToList(); Console.WriteLine(r1); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C c3 = new C { 100, 200, 300 }; C r1 = new C(); foreach (var (x, y, z) in c1.SelectMany(x => c2.SelectMany(y => c3.Select(z => (x, y, z))))) { var g = x + y + z; if (x + y / 10 + z / 100 < 6) { r1.Add(g); } } Console.WriteLine(r1); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListTypeReplacement02() { var source = @" using System.Linq; using System; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C r1 = new C(); [|foreach (int x in c1) { foreach (var y in c2) { if (Equals(x, y / 10)) { var z = x + y; r1.Add(z); } } }|] Console.WriteLine(r1); } } "; var queryOutput = @" using System.Linq; using System; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C r1 = (from int x in c1 from y in c2 where Equals(x, y / 10) let z = x + y select z).ToList(); Console.WriteLine(r1); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Linq; using System; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C r1 = new C(); foreach (var (x, y) in c1.SelectMany(x => c2.Where(y => Equals(x, y / 10)).Select(y => (x, y)))) { var z = x + y; r1.Add(z); } Console.WriteLine(r1); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListPropertyAssignment() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A = new List<int>(); [|foreach (var x in nums) { c.A.Add(x + 1); }|] } class C { public List<int> A { get; set; } } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A = (from x in nums select x + 1).ToList(); } class C { public List<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A = (nums.Select(x => x + 1)).ToList(); } class C { public List<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListPropertyAssignmentNoDeclaration() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { void M() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); [|foreach (var x in nums) { c.A.Add(x + 1); }|] } class C { public List<int> A { get; set; } } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; public class Test { void M() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A.AddRange(from x in nums select x + 1); } class C { public List<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; public class Test { void M() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A.AddRange(nums.Select(x => x + 1)); } class C { public List<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListNoInitialization() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public List<int> A { get; set; } void M() { [|foreach (var x in new int[] { 1, 2, 3, 4 }) { A.Add(x + 1); }|] } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; public class Test { public List<int> A { get; set; } void M() { A.AddRange(from x in new int[] { 1, 2, 3, 4 } select x + 1); } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; public class Test { public List<int> A { get; set; } void M() { A.AddRange((new int[] { 1, 2, 3, 4 }).Select(x => x + 1)); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListOverride() { var source = @" using System.Collections.Generic; using System.Linq; public static class C { public static void Add<T>(this List<T> list, T value, T anotherValue) { } } public class Test { void M() { var list = new List<int>(); [|foreach (var x in new int[] { 1, 2, 3, 4 }) { list.Add(x + 1, x); }|] } }"; await TestMissingAsync(source); } #endregion #region In Count [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int i = 0, cnt = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int i = 0, cnt = (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int i = 0, cnt = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationNotLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int cnt = 0, i = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int cnt = 0, i = 0; cnt += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int cnt = 0, i = 0; cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInParameter() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { c++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInParameterAssignedToZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { c++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInParameterAssignedToNonZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = 5; [|foreach (int n1 in nums) { foreach (int n2 in nums) { c++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = 5; c += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = 5; c += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInDeclarationMergeToReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { var cnt = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { return (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInDeclarationConversion() { var source = @" using System.Collections.Generic; using System.Linq; class C { double M(IEnumerable<int> nums) { double c = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { c++; } }|] return c; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { double M(IEnumerable<int> nums) { return (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { double M(IEnumerable<int> nums) { return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationMergeToReturnLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0, cnt = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0; return (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0; return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationLastButNotZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0, cnt = 5; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0, cnt = 5; cnt += (from int n1 in nums from int n2 in nums select n1).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0, cnt = 5; cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationMergeToReturnNotLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 0, c = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 0, c = 0; cnt += (from int n1 in nums from int n2 in nums select n1).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 0, c = 0; cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationNonZeroToReturnNotLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 5, c = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 5, c = 0; cnt += (from int n1 in nums from int n2 in nums select n1).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 5, c = 0; cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInAssignmentToZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; cnt = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; return (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInAssignmentToNonZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; cnt = 5; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; cnt = 5; cnt += (from int n1 in nums from int n2 in nums select n1).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; cnt = 5; cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInParameterAssignedToZeroAndReturned() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums, int c) { c = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { c++; } }|] return c; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums, int c) { c = (from int n1 in nums from int n2 in nums select n1).Count(); return c; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums, int c) { c = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); return c; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountDeclareWithNonZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 5; [|foreach (int n1 in nums) { foreach (int n2 in nums) { count++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 5; count += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 5; count += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountAssignWithZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int count = 1; count = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { count++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int count = 1; count = (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int count = 1; count = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountAssignWithNonZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 0; count = 4; [|foreach (int n1 in nums) { foreach (int n2 in nums) { count++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 0; count = 4; count += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 0; count = 4; count += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountAssignPropertyAssignedToZero() { var source = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { a.B++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountAssignPropertyAssignedToNonZero() { var source = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = 5; [|foreach (int n1 in nums) { foreach (int n2 in nums) { a.B++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = 5; a.B += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = 5; a.B += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountAssignPropertyNotKnownAssigned() { var source = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { a.B++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountIQueryableInInvocation() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int c = 0; [|foreach (int n1 in nums.AsQueryable()) { c++; }|] } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int c = (from int n1 in nums.AsQueryable() select n1).Count(); } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int c = (nums.AsQueryable()).Count(); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } #endregion #region Comments [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsYieldReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|// 1 foreach /* 2 */( /* 3 */ var /* 4 */ x /* 5 */ in /* 6 */ nums /* 7 */)// 8 { // 9 /* 10 */ foreach /* 11 */ (/* 12 */ int /* 13 */ y /* 14 */ in /* 15 */ nums /* 16 */)/* 17 */ // 18 {// 19 /*20 */ if /* 21 */(/* 22 */ x > 2 /* 23 */) // 24 { // 25 /* 26 */ yield /* 27 */ return /* 28 */ x * y /* 29 */; // 30 /* 31 */ }// 32 /* 33 */ } // 34 /* 35 */ }|] /* 36 */ /* 37 */ yield /* 38 */ break/* 39*/; // 40 } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return // 25 // 1 from/* 3 *//* 2 *//* 4 */x /* 5 */ in/* 6 */nums/* 7 */// 8 // 9 /* 10 */ from/* 12 *//* 11 */int /* 13 */ y /* 14 */ in/* 15 */nums/* 16 *//* 17 */// 18 // 19 /*20 */ where/* 21 *//* 22 */x > 2/* 23 */// 24 /* 26 *//* 27 *//* 28 */ select x * y/* 29 *//* 31 */// 32 /* 33 */// 34 /* 35 *//* 36 */// 30 /* 37 *//* 38 *//* 39*/// 40 ; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return nums /* 7 */.SelectMany( // 1 /* 2 */// 25 /* 4 */x /* 5 */ => nums /* 16 */.Where( /*20 *//* 21 */// 19 y => /* 22 */x > 2/* 23 */// 24 ).Select( // 9 /* 10 *//* 11 *//* 13 */y /* 14 */ => /* 26 *//* 27 *//* 28 */x * y/* 29 *//* 31 */// 32 /* 33 */// 34 /* 35 *//* 36 */// 30 /* 37 *//* 38 *//* 39*/// 40 /* 12 *//* 15 *//* 17 */// 18 )/* 3 *//* 6 */// 8 ); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsToList() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { /* 1 */ var /* 2 */ list /* 3 */ = /* 4 */ new List<int>(); // 5 /* 6 */ [|foreach /* 7 */ (/* 8 */ var /* 9 */ x /* 10 */ in /* 11 */ nums /* 12 */) // 13 /* 14 */{ // 15 /* 16 */var /* 17 */ y /* 18 */ = /* 19 */ x + 1 /* 20 */; //21 /* 22 */ list.Add(/* 23 */y /* 24 */) /* 25 */;//26 /*27*/} //28|] /*29*/return /*30*/ list /*31*/; //32 } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { /*29*/ return /*30*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5 /*31*/ ( /* 6 */from/* 8 *//* 7 *//* 9 */x /* 10 */ in/* 11 */nums/* 12 */// 13 /* 14 */// 15 /* 16 *//* 17 */ let y /* 18 */ = /* 19 */ x + 1/* 20 *///21 select y/* 24 *//*27*///28 ).ToList()/* 22 *//* 23 *//* 25 *///26 ; //32 } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); // No linq refactoring offered due to variable declaration in outermost foreach. await TestActionCountAsync(source, count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsToList_02() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { /* 1 */ var /* 2 */ list /* 3 */ = /* 4 */ new List<int>(); // 5 /* 6 */ [|foreach /* 7 */ (/* 8 */ var /* 9 */ x /* 10 */ in /* 11 */ nums /* 12 */) // 13 /* 14 */{ // 15 /* 16 */ list.Add(/* 17 */ x + 1 /* 18 */) /* 19 */;//20 /*21*/} //22|] /*23*/return /*24*/ list /*25*/; //26 } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { /*23*/ return /*24*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5 /*25*/ ( /* 14 */// 15 /* 6 */from/* 8 *//* 7 *//* 9 */x /* 10 */ in/* 11 */nums/* 12 */// 13 select x + 1/* 18 *//*21*///22 ).ToList()/* 16 *//* 17 *//* 19 *///20 ; //26 } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { /*23*/ return /*24*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5 /*25*/ (nums /* 12 */.Select( /* 6 *//* 7 *//* 14 */// 15 /* 9 */x /* 10 */ => x + 1/* 18 *//*21*///22 /* 8 *//* 11 */// 13 )).ToList()/* 16 *//* 17 *//* 19 *///20 ; //26 } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsCount() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { /* 1 */ var /* 2 */ c /* 3 */ = /* 4 */ 0; // 5 /* 6 */ [| foreach /* 7 */ (/* 8 */ var /* 9 */ x /* 10 */ in /* 11 */ nums /* 12 */) // 13 /* 14 */{ // 15 /* 16 */ c++ /* 17 */;//18 /*19*/}|] //20 /*21*/return /*22*/ c /*23*/; //24 } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { /*21*/ return /*22*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5 /*23*/ ( /* 14 */// 15 /* 6 */from/* 8 *//* 7 *//* 9 */x /* 10 */ in/* 11 */nums/* 12 */// 13 select x/* 10 *//*19*///20 ).Count()/* 16 *//* 17 *///18 ; //24 } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { /*21*/ return /*22*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5 /*23*/ (nums /* 12 *//* 6 *//* 7 *//* 14 */// 15 /* 9 *//* 10 *//* 10 *//*19*///20 /* 8 *//* 11 */// 13 ).Count()/* 16 *//* 17 *///18 ; //24 } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsDefault() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|/* 1 */ foreach /* 2 */(int /* 3 */ n1 /* 4 */in /* 5 */ nums /* 6 */)// 7 /* 8*/{// 9 /* 10 */int /* 11 */ a /* 12 */ = /* 13 */ n1 + n1 /* 14*/, /* 15 */ b /*16*/ = /*17*/ n1 * n1/*18*/;//19 /*20*/Console.WriteLine(a + b);//21 /*22*/}/*23*/|] } }"; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var (a /* 12 */ , b /*16*/ ) in /* 1 */from/* 2 */int /* 3 */ n1 /* 4 */in/* 5 */nums/* 6 */// 7 /* 8*/// 9 /* 10 *//* 11 */ let a /* 12 */ = /* 13 */ n1 + n1/* 14*//* 15 */ let b /*16*/ = /*17*/ n1 * n1/*18*///19 select (a /* 12 */ , b /*16*/ )/*22*//*23*/) { /*20*/ Console.WriteLine(a + b);//21 } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); // No linq refactoring offered due to variable declaration(s) in outermost foreach. await TestActionCountAsync(source, count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsDefault_02() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|/* 1 */ foreach /* 2 */(int /* 3 */ n1 /* 4 */in /* 5 */ nums /* 6 */)// 7 /* 8*/{// 9 /* 10 */ if /* 11 */ (/* 12 */ n1 /* 13 */ > /* 14 */ 0/* 15 */ ) // 16 /* 17 */{ // 18 /*19*/Console.WriteLine(n1);//20 /* 21 */} // 22 /*23*/}/*24*/|] } }"; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var n1 /* 4 */in /* 17 */// 18 /* 1 */from/* 2 */int /* 3 */ n1 /* 4 */in/* 5 */nums/* 6 */// 7 /* 8*/// 9 /* 10 */ where/* 11 *//* 12 */n1 /* 13 */ > /* 14 */ 0/* 15 */// 16 select n1/* 4 *//* 21 */// 22 /*23*//*24*/ ) { /*19*/ Console.WriteLine(n1);//20 } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var n1 /* 4 */in nums /* 6 */.Where( /* 10 *//* 11 *//* 8*/// 9 n1 => /* 12 */n1 /* 13 */ > /* 14 */ 0/* 15 */// 16 ) /* 1 *//* 2 *//* 17 */// 18 /* 3 *//* 4 *//* 4 *//* 21 */// 22 /*23*//*24*//* 5 */// 7 ) { /*19*/ Console.WriteLine(n1);//20 } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } #endregion #region Preprocessor directives [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task NoConversionPreprocessorDirectives() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|foreach(var x in nums) { #if (true) yield return x + 1; #endif }|] } }"; // Cannot convert expressions with preprocessor directives await TestMissingAsync(source); } #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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.ConvertLinq { public class ConvertForEachToLinqQueryTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery.CSharpConvertForEachToLinqQueryProvider(); #region Query Expressions [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryForForWhere() { var source = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; [|foreach (var x1 in c1) { foreach (var x2 in c2) { if (object.Equals(x1, x2 / 10)) { yield return x1 + x2; } } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; return from x1 in c1 from x2 in c2 where object.Equals(x1, x2 / 10) select x1 + x2; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; return c1.SelectMany(x1 => c2.Where(x2 => object.Equals(x1, x2 / 10)).Select(x2 => x1 + x2)); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryWithEscapedSymbols() { var source = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; [|foreach (var @object in c1) { foreach (var x2 in c2) { yield return @object + x2; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; return from @object in c1 from x2 in c2 select @object + x2; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; return c1.SelectMany(@object => c2.Select(x2 => @object + x2)); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryForVarForWhere() { var source = @" using System.Linq; class C { IEnumerable<int> M() { [|foreach (var num in new int[] { 1, 2 }) { var n1 = num + 1; foreach (var a in new int[] { 5, 6 }) { foreach (var x1 in new int[] { 3, 4 }) { if (object.Equals(num, x1)) { foreach (var x2 in new int[] { 7, 8 }) { if (object.Equals(num, x2)) { var n2 = x2 - 1; yield return n2 + n1; } } } } }|] } } }"; var queryOutput = @" using System.Linq; class C { IEnumerable<int> M() { return from num in new int[] { 1, 2 } let n1 = num + 1 from a in new int[] { 5, 6 } from x1 in new int[] { 3, 4 } where object.Equals(num, x1) from x2 in new int[] { 7, 8 } where object.Equals(num, x2) let n2 = x2 - 1 select n2 + n1; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); // No linq refactoring offered due to variable declaration within the outermost foreach. await TestActionCountAsync(source, count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryForVarForWhere_02() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { [|foreach (var num in new int[] { 1, 2 }) { foreach (var a in new int[] { 5, 6 }) { foreach (var x1 in new int[] { 3, 4 }) { if (object.Equals(num, x1)) { foreach (var x2 in new int[] { 7, 8 }) { if (object.Equals(num, x2)) { var n1 = num + 1; var n2 = x2 - 1; yield return n2 + n1; } } } } }|] } } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { return from num in new int[] { 1, 2 } from a in new int[] { 5, 6 } from x1 in new int[] { 3, 4 } where object.Equals(num, x1) from x2 in new int[] { 7, 8 } where object.Equals(num, x2) let n1 = num + 1 let n2 = x2 - 1 select n2 + n1; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { foreach (var (num, x2) in (new int[] { 1, 2 }).SelectMany(num => (new int[] { 5, 6 }).SelectMany(a => (new int[] { 3, 4 }).Where(x1 => object.Equals(num, x1)).SelectMany(x1 => (new int[] { 7, 8 }).Where(x2 => object.Equals(num, x2)).Select(x2 => (num, x2)))))) { var n1 = num + 1; var n2 = x2 - 1; yield return n2 + n1; } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryForVarForWhere_03() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { [|foreach (var num in new int[] { 1, 2 }) { foreach (var a in new int[] { 5, 6 }) { foreach (var x1 in new int[] { 3, 4 }) { var n1 = num + 1; if (object.Equals(num, x1)) { foreach (var x2 in new int[] { 7, 8 }) { if (object.Equals(num, x2)) { var n2 = x2 - 1; yield return n2 + n1; } } } } }|] } } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { return from num in new int[] { 1, 2 } from a in new int[] { 5, 6 } from x1 in new int[] { 3, 4 } let n1 = num + 1 where object.Equals(num, x1) from x2 in new int[] { 7, 8 } where object.Equals(num, x2) let n2 = x2 - 1 select n2 + n1; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { foreach (var (num, x1) in (new int[] { 1, 2 }).SelectMany(num => (new int[] { 5, 6 }).SelectMany(a => (new int[] { 3, 4 }).Select(x1 => (num, x1))))) { var n1 = num + 1; if (object.Equals(num, x1)) { foreach (var x2 in new int[] { 7, 8 }) { if (object.Equals(num, x2)) { var n2 = x2 - 1; yield return n2 + n1; } } } } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryLet() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { void M() { List<int> c1 = new List<int>{ 1, 2, 3 }; List<int> r1 = new List<int>(); [|foreach (int x in c1) { var g = x * 10; var z = g + x*100; var a = 5 + z; r1.Add(x + z - a); }|] } }"; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class Query { void M() { List<int> c1 = new List<int>{ 1, 2, 3 }; List<int> r1 = (from int x in c1 let g = x * 10 let z = g + x * 100 let a = 5 + z select x + z - a).ToList(); } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); // No linq invocation refactoring offered due to variable declaration(s) in topmost foreach. await TestActionCountAsync(source, count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryEmptyDeclarations() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { void M() { [|foreach (int x in new[] {1,2}) { int a = 3, b, c = 1; if (x > c) { b = 0; Console.Write(a + x + b); } }|] } }"; await TestMissingInRegularAndScriptAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryWhereClause() { var source = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; [|foreach (var x in nums) { if (x > 2) { yield return x; } }|] } }"; var queryOutput = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; return from x in nums where x > 2 select x; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; return nums.Where(x => x > 2); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryOverQueries() { var source = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; [|foreach (var y in from x in nums select x) { foreach (var z in from x in nums select x) { yield return y; } }|] } }"; var queryOutput = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; return from y in from x in nums select x from z in from x in nums select x select y; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; return (from x in nums select x).SelectMany(y => (from x in nums select x).Select(z => y)); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryNoVariablesUsed() { var source = @" using System; using System.Linq; class C { void M() { [|foreach (var a in new[] { 1 }) { foreach (var b in new[] { 2 }) { System.Console.Write(0); } }|] } }"; var queryOutput = @" using System; using System.Linq; class C { void M() { foreach (var _ in from a in new[] { 1 } from b in new[] { 2 } select new { }) { System.Console.Write(0); } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { void M() { foreach (var _ in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => new { }))) { System.Console.Write(0); } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryNoBlock() { var source = @" using System; using System.Linq; class C { void M() { [|foreach (var a in new[] { 1 }) foreach (var b in new[] { 2 }) System.Console.Write(a);|] } }"; var queryOutput = @" using System; using System.Linq; class C { void M() { foreach (var a in from a in new[] { 1 } from b in new[] { 2 } select a) { System.Console.Write(a); } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { void M() { foreach (var a in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => a))) { System.Console.Write(a); } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QuerySelectExpression() { var source = @" using System; using System.Linq; class C { void M() { [|foreach (var a in new[] { 1 }) foreach (var b in new[] { 2 }) Console.Write(a + b);|] } }"; var queryOutput = @" using System; using System.Linq; class C { void M() { foreach (var (a, b) in from a in new[] { 1 } from b in new[] { 2 } select (a, b)) { Console.Write(a + b); } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { void M() { foreach (var (a, b) in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => (a, b)))) { Console.Write(a + b); } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QuerySelectMultipleExpressions() { var source = @" using System; using System.Linq; class C { void M() { [|foreach (var a in new[] { 1 }) foreach (var b in new[] { 2 }) { Console.Write(a + b); Console.Write(a * b); }|] } }"; var queryOutput = @" using System; using System.Linq; class C { void M() { foreach (var (a, b) in from a in new[] { 1 } from b in new[] { 2 } select (a, b)) { Console.Write(a + b); Console.Write(a * b); } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { void M() { foreach (var (a, b) in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => (a, b)))) { Console.Write(a + b); Console.Write(a * b); } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task EmptyBody() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in from int n1 in nums from int n2 in nums select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { }))) { } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task EmptyBodyNoBlock() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums); }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in from int n1 in nums from int n2 in nums select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { }))) { } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task AddUsingToExistingList() { var source = @" using System.Collections.Generic; class C { void M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums); }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in from int n1 in nums from int n2 in nums select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { }))) { } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task AddFirstUsing() { var source = @" class C { void M(int[] nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums); }|] } } "; var queryOutput = @"using System.Linq; class C { void M(int[] nums) { foreach (var _ in from int n1 in nums from int n2 in nums select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @"using System.Linq; class C { void M(int[] nums) { foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { }))) { } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task EmptyBodyDeclarationAsLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { var a = n1 + n2; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in from int n1 in nums from int n2 in nums let a = n1 + n2 select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var (n1, n2) in nums.SelectMany(n1 => nums.Select(n2 => (n1, n2)))) { var a = n1 + n2; } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task EmptyBodyMultipleDeclarationsAsLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { int a = n1 + n2, b = n1 * n2; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in from int n1 in nums from int n2 in nums let a = n1 + n2 let b = n1 * n2 select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var (n1, n2) in nums.SelectMany(n1 => nums.Select(n2 => (n1, n2)))) { int a = n1 + n2, b = n1 * n2; } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } #endregion #region Assignments, Declarations, Returns [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnInvocationAndYieldReturn() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { yield return N(n1); } }|] } int N(int n) => n; } "; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums from int n2 in nums select N(n1); } int N(int n) => n; } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return nums.SelectMany(n1 => nums.Select(n2 => N(n1))); } int N(int n) => n; } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task BlockBodiedProperty() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query1 { get { [|foreach (var x in _nums) { yield return x + 1; }|] } } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query1 { get { return from x in _nums select x + 1; } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query1 { get { return _nums.Select(x => x + 1); } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnIEnumerable() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums from int n2 in nums select n1; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return nums.SelectMany(n1 => nums.Select(n2 => n1)); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnIEnumerableWithYieldReturnAndLocalFunction() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<IEnumerable<int>> M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { yield return f(n1); } }|] yield break; IEnumerable<int> f(int a) { yield return a; } } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<IEnumerable<int>> M(IEnumerable<int> nums) { return from int n1 in nums from int n2 in nums select f(n1); IEnumerable<int> f(int a) { yield return a; } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<IEnumerable<int>> M(IEnumerable<int> nums) { return nums.SelectMany(n1 => nums.Select(n2 => f(n1))); IEnumerable<int> f(int a) { yield return a; } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnIEnumerablePartialMethod() { var source = @" using System.Collections.Generic; using System.Linq; partial class C { partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { partial IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } }|] yield break; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; partial class C { partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { partial IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums from int n2 in nums select n1; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; partial class C { partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { partial IEnumerable<int> M(IEnumerable<int> nums) { return nums.SelectMany(n1 => nums.Select(n2 => n1)); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnIEnumerableExtendedPartialMethod() { var source = @" using System.Collections.Generic; using System.Linq; partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } }|] yield break; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums from int n2 in nums select n1; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums) { return nums.SelectMany(n1 => nums.Select(n2 => n1)); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] [WorkItem(31784, "https://github.com/dotnet/roslyn/issues/31784")] public async Task QueryWhichRequiresSelectManyWithIdentityLambda() { var source = @" using System.Collections.Generic; class C { IEnumerable<int> M() { [|foreach (var x in new[] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 } }) { foreach (var y in x) { yield return y; } }|] } } "; var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { return (new[] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 } }).SelectMany(x => x); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } #endregion #region In foreach [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryInForEachWithSameVariableNameAndDifferentType() { var source = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class B : A { } class C { void M(IEnumerable<int> nums) { [|foreach (B a in nums) { foreach (A c in nums) { Console.Write(a.ToString()); } }|] } } "; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class B : A { } class C { void M(IEnumerable<int> nums) { foreach (var a in from B a in nums from A c in nums select a) { Console.Write(a.ToString()); } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class B : A { } class C { void M(IEnumerable<int> nums) { foreach (var a in nums.SelectMany(a => nums.Select(c => a))) { Console.Write(a.ToString()); } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryInForEachWithSameVariableNameAndSameType() { var source = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class C { void M(IEnumerable<int> nums) { [|foreach (A a in nums) { foreach (A c in nums) { Console.Write(a.ToString()); } }|] } } "; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class C { void M(IEnumerable<int> nums) { foreach (var a in from A a in nums from A c in nums select a) { Console.Write(a.ToString()); } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class C { void M(IEnumerable<int> nums) { foreach (var a in nums.SelectMany(a => nums.Select(c => a))) { Console.Write(a.ToString()); } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryInForEachWithConvertedType() { var source = @" using System; using System.Collections.Generic; static class Extensions { public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null; } class C { public static implicit operator int(C x) { throw null; } public static implicit operator C(int x) { throw null; } IEnumerable<C> Test() { [|foreach (var x in new[] { 1, 2, 3 }) { yield return x; }|] } } "; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; static class Extensions { public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null; } class C { public static implicit operator int(C x) { throw null; } public static implicit operator C(int x) { throw null; } IEnumerable<C> Test() { return from x in new[] { 1, 2, 3 } select x; } } "; await TestAsync(source, queryOutput, parseOptions: null); var linqInvocationOutput = @" using System; using System.Collections.Generic; using System.Linq; static class Extensions { public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null; } class C { public static implicit operator int(C x) { throw null; } public static implicit operator C(int x) { throw null; } IEnumerable<C> Test() { return new[] { 1, 2, 3 }; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task IQueryableConvertedToIEnumerableInReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums.AsQueryable()) { yield return n1; }|] yield break; } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums.AsQueryable() select n1; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return nums.AsQueryable(); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnIQueryableConvertedToIEnumerableInAssignment() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums.AsQueryable()) { yield return n1; }|] } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums.AsQueryable() select n1; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return nums.AsQueryable(); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } #endregion #region In ToList [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListLastDeclarationMerge() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list0 = new List<int>(), list = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list0 = new List<int>(); return (from int n1 in nums from int n2 in nums select n1).ToList(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list0 = new List<int>(); return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListParameterizedConstructor() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(nums); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(nums); list.AddRange(from int n1 in nums from int n2 in nums select n1); return list; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(nums); list.AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1))); return list; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListWithListInitializer() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>() { 1, 2, 3 }; [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>() { 1, 2, 3 }; list.AddRange(from int n1 in nums from int n2 in nums select n1); return list; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>() { 1, 2, 3 }; list.AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1))); return list; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListWithEmptyArgumentList() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int> { }; [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { return (from int n1 in nums from int n2 in nums select n1).ToList(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListNotLastDeclaration() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(), list1 = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(), list1 = new List<int>(); list.AddRange(from int n1 in nums from int n2 in nums select n1); return list; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(), list1 = new List<int>(); list.AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1))); return list; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListAssignToParameter() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums, List<int> list) { list = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums, List<int> list) { list = (from int n1 in nums from int n2 in nums select n1).ToList(); return list; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums, List<int> list) { list = (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); return list; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListToArrayElement() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { lists[0].Add(n1); } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { lists[0].AddRange(from int n1 in nums from int n2 in nums select n1); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { lists[0].AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1))); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListToNewArrayElement() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { lists[0] = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { lists[0].Add(n1); } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { lists[0] = (from int n1 in nums from int n2 in nums select n1).ToList(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { lists[0] = (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListHashSetNoConversion() { var source = @" using System.Collections.Generic; class C { void M(IEnumerable<int> nums) { var hashSet = new HashSet<int>(); [|foreach (int n1 in nums) { hashSet.Add(n1); }|] } } "; await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListMergeWithReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { var list = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { return (from int n1 in nums from int n2 in nums select n1).ToList(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListSeparateDeclarationAndAssignmentMergeWithReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list; list = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list; return (from int n1 in nums from int n2 in nums select n1).ToList(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list; return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListSeparateDeclarationAndAssignment() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { List<int> list; list = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list.Count; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { List<int> list; list = (from int n1 in nums from int n2 in nums select n1).ToList(); return list.Count; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { List<int> list; list = (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); return list.Count; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListTypeReplacement01() { var source = @" using System; using System.Linq; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C c3 = new C { 100, 200, 300 }; C r1 = new C(); [|foreach (int x in c1) { foreach (int y in c2) { foreach (int z in c3) { var g = x + y + z; if (x + y / 10 + z / 100 < 6) { r1.Add(g); } } } }|] Console.WriteLine(r1); } } "; var queryOutput = @" using System; using System.Linq; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C c3 = new C { 100, 200, 300 }; C r1 = (from int x in c1 from int y in c2 from int z in c3 let g = x + y + z where x + y / 10 + z / 100 < 6 select g).ToList(); Console.WriteLine(r1); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C c3 = new C { 100, 200, 300 }; C r1 = new C(); foreach (var (x, y, z) in c1.SelectMany(x => c2.SelectMany(y => c3.Select(z => (x, y, z))))) { var g = x + y + z; if (x + y / 10 + z / 100 < 6) { r1.Add(g); } } Console.WriteLine(r1); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListTypeReplacement02() { var source = @" using System.Linq; using System; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C r1 = new C(); [|foreach (int x in c1) { foreach (var y in c2) { if (Equals(x, y / 10)) { var z = x + y; r1.Add(z); } } }|] Console.WriteLine(r1); } } "; var queryOutput = @" using System.Linq; using System; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C r1 = (from int x in c1 from y in c2 where Equals(x, y / 10) let z = x + y select z).ToList(); Console.WriteLine(r1); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Linq; using System; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C r1 = new C(); foreach (var (x, y) in c1.SelectMany(x => c2.Where(y => Equals(x, y / 10)).Select(y => (x, y)))) { var z = x + y; r1.Add(z); } Console.WriteLine(r1); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListPropertyAssignment() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A = new List<int>(); [|foreach (var x in nums) { c.A.Add(x + 1); }|] } class C { public List<int> A { get; set; } } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A = (from x in nums select x + 1).ToList(); } class C { public List<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A = (nums.Select(x => x + 1)).ToList(); } class C { public List<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListPropertyAssignmentNoDeclaration() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { void M() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); [|foreach (var x in nums) { c.A.Add(x + 1); }|] } class C { public List<int> A { get; set; } } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; public class Test { void M() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A.AddRange(from x in nums select x + 1); } class C { public List<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; public class Test { void M() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A.AddRange(nums.Select(x => x + 1)); } class C { public List<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListNoInitialization() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public List<int> A { get; set; } void M() { [|foreach (var x in new int[] { 1, 2, 3, 4 }) { A.Add(x + 1); }|] } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; public class Test { public List<int> A { get; set; } void M() { A.AddRange(from x in new int[] { 1, 2, 3, 4 } select x + 1); } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; public class Test { public List<int> A { get; set; } void M() { A.AddRange((new int[] { 1, 2, 3, 4 }).Select(x => x + 1)); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListOverride() { var source = @" using System.Collections.Generic; using System.Linq; public static class C { public static void Add<T>(this List<T> list, T value, T anotherValue) { } } public class Test { void M() { var list = new List<int>(); [|foreach (var x in new int[] { 1, 2, 3, 4 }) { list.Add(x + 1, x); }|] } }"; await TestMissingAsync(source); } #endregion #region In Count [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int i = 0, cnt = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int i = 0, cnt = (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int i = 0, cnt = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationNotLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int cnt = 0, i = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int cnt = 0, i = 0; cnt += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int cnt = 0, i = 0; cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInParameter() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { c++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInParameterAssignedToZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { c++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInParameterAssignedToNonZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = 5; [|foreach (int n1 in nums) { foreach (int n2 in nums) { c++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = 5; c += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = 5; c += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInDeclarationMergeToReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { var cnt = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { return (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInDeclarationConversion() { var source = @" using System.Collections.Generic; using System.Linq; class C { double M(IEnumerable<int> nums) { double c = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { c++; } }|] return c; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { double M(IEnumerable<int> nums) { return (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { double M(IEnumerable<int> nums) { return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationMergeToReturnLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0, cnt = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0; return (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0; return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationLastButNotZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0, cnt = 5; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0, cnt = 5; cnt += (from int n1 in nums from int n2 in nums select n1).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0, cnt = 5; cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationMergeToReturnNotLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 0, c = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 0, c = 0; cnt += (from int n1 in nums from int n2 in nums select n1).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 0, c = 0; cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationNonZeroToReturnNotLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 5, c = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 5, c = 0; cnt += (from int n1 in nums from int n2 in nums select n1).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 5, c = 0; cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInAssignmentToZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; cnt = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; return (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInAssignmentToNonZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; cnt = 5; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; cnt = 5; cnt += (from int n1 in nums from int n2 in nums select n1).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; cnt = 5; cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInParameterAssignedToZeroAndReturned() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums, int c) { c = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { c++; } }|] return c; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums, int c) { c = (from int n1 in nums from int n2 in nums select n1).Count(); return c; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums, int c) { c = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); return c; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountDeclareWithNonZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 5; [|foreach (int n1 in nums) { foreach (int n2 in nums) { count++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 5; count += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 5; count += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountAssignWithZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int count = 1; count = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { count++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int count = 1; count = (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int count = 1; count = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountAssignWithNonZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 0; count = 4; [|foreach (int n1 in nums) { foreach (int n2 in nums) { count++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 0; count = 4; count += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 0; count = 4; count += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountAssignPropertyAssignedToZero() { var source = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { a.B++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountAssignPropertyAssignedToNonZero() { var source = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = 5; [|foreach (int n1 in nums) { foreach (int n2 in nums) { a.B++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = 5; a.B += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = 5; a.B += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountAssignPropertyNotKnownAssigned() { var source = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { a.B++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountIQueryableInInvocation() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int c = 0; [|foreach (int n1 in nums.AsQueryable()) { c++; }|] } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int c = (from int n1 in nums.AsQueryable() select n1).Count(); } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int c = (nums.AsQueryable()).Count(); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } #endregion #region Comments [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsYieldReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|// 1 foreach /* 2 */( /* 3 */ var /* 4 */ x /* 5 */ in /* 6 */ nums /* 7 */)// 8 { // 9 /* 10 */ foreach /* 11 */ (/* 12 */ int /* 13 */ y /* 14 */ in /* 15 */ nums /* 16 */)/* 17 */ // 18 {// 19 /*20 */ if /* 21 */(/* 22 */ x > 2 /* 23 */) // 24 { // 25 /* 26 */ yield /* 27 */ return /* 28 */ x * y /* 29 */; // 30 /* 31 */ }// 32 /* 33 */ } // 34 /* 35 */ }|] /* 36 */ /* 37 */ yield /* 38 */ break/* 39*/; // 40 } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return // 25 // 1 from/* 3 *//* 2 *//* 4 */x /* 5 */ in/* 6 */nums/* 7 */// 8 // 9 /* 10 */ from/* 12 *//* 11 */int /* 13 */ y /* 14 */ in/* 15 */nums/* 16 *//* 17 */// 18 // 19 /*20 */ where/* 21 *//* 22 */x > 2/* 23 */// 24 /* 26 *//* 27 *//* 28 */ select x * y/* 29 *//* 31 */// 32 /* 33 */// 34 /* 35 *//* 36 */// 30 /* 37 *//* 38 *//* 39*/// 40 ; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return nums /* 7 */.SelectMany( // 1 /* 2 */// 25 /* 4 */x /* 5 */ => nums /* 16 */.Where( /*20 *//* 21 */// 19 y => /* 22 */x > 2/* 23 */// 24 ).Select( // 9 /* 10 *//* 11 *//* 13 */y /* 14 */ => /* 26 *//* 27 *//* 28 */x * y/* 29 *//* 31 */// 32 /* 33 */// 34 /* 35 *//* 36 */// 30 /* 37 *//* 38 *//* 39*/// 40 /* 12 *//* 15 *//* 17 */// 18 )/* 3 *//* 6 */// 8 ); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsToList() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { /* 1 */ var /* 2 */ list /* 3 */ = /* 4 */ new List<int>(); // 5 /* 6 */ [|foreach /* 7 */ (/* 8 */ var /* 9 */ x /* 10 */ in /* 11 */ nums /* 12 */) // 13 /* 14 */{ // 15 /* 16 */var /* 17 */ y /* 18 */ = /* 19 */ x + 1 /* 20 */; //21 /* 22 */ list.Add(/* 23 */y /* 24 */) /* 25 */;//26 /*27*/} //28|] /*29*/return /*30*/ list /*31*/; //32 } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { /*29*/ return /*30*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5 /*31*/ ( /* 6 */from/* 8 *//* 7 *//* 9 */x /* 10 */ in/* 11 */nums/* 12 */// 13 /* 14 */// 15 /* 16 *//* 17 */ let y /* 18 */ = /* 19 */ x + 1/* 20 *///21 select y/* 24 *//*27*///28 ).ToList()/* 22 *//* 23 *//* 25 *///26 ; //32 } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); // No linq refactoring offered due to variable declaration in outermost foreach. await TestActionCountAsync(source, count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsToList_02() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { /* 1 */ var /* 2 */ list /* 3 */ = /* 4 */ new List<int>(); // 5 /* 6 */ [|foreach /* 7 */ (/* 8 */ var /* 9 */ x /* 10 */ in /* 11 */ nums /* 12 */) // 13 /* 14 */{ // 15 /* 16 */ list.Add(/* 17 */ x + 1 /* 18 */) /* 19 */;//20 /*21*/} //22|] /*23*/return /*24*/ list /*25*/; //26 } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { /*23*/ return /*24*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5 /*25*/ ( /* 14 */// 15 /* 6 */from/* 8 *//* 7 *//* 9 */x /* 10 */ in/* 11 */nums/* 12 */// 13 select x + 1/* 18 *//*21*///22 ).ToList()/* 16 *//* 17 *//* 19 *///20 ; //26 } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { /*23*/ return /*24*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5 /*25*/ (nums /* 12 */.Select( /* 6 *//* 7 *//* 14 */// 15 /* 9 */x /* 10 */ => x + 1/* 18 *//*21*///22 /* 8 *//* 11 */// 13 )).ToList()/* 16 *//* 17 *//* 19 *///20 ; //26 } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsCount() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { /* 1 */ var /* 2 */ c /* 3 */ = /* 4 */ 0; // 5 /* 6 */ [| foreach /* 7 */ (/* 8 */ var /* 9 */ x /* 10 */ in /* 11 */ nums /* 12 */) // 13 /* 14 */{ // 15 /* 16 */ c++ /* 17 */;//18 /*19*/}|] //20 /*21*/return /*22*/ c /*23*/; //24 } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { /*21*/ return /*22*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5 /*23*/ ( /* 14 */// 15 /* 6 */from/* 8 *//* 7 *//* 9 */x /* 10 */ in/* 11 */nums/* 12 */// 13 select x/* 10 *//*19*///20 ).Count()/* 16 *//* 17 *///18 ; //24 } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { /*21*/ return /*22*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5 /*23*/ (nums /* 12 *//* 6 *//* 7 *//* 14 */// 15 /* 9 *//* 10 *//* 10 *//*19*///20 /* 8 *//* 11 */// 13 ).Count()/* 16 *//* 17 *///18 ; //24 } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsDefault() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|/* 1 */ foreach /* 2 */(int /* 3 */ n1 /* 4 */in /* 5 */ nums /* 6 */)// 7 /* 8*/{// 9 /* 10 */int /* 11 */ a /* 12 */ = /* 13 */ n1 + n1 /* 14*/, /* 15 */ b /*16*/ = /*17*/ n1 * n1/*18*/;//19 /*20*/Console.WriteLine(a + b);//21 /*22*/}/*23*/|] } }"; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var (a /* 12 */ , b /*16*/ ) in /* 1 */from/* 2 */int /* 3 */ n1 /* 4 */in/* 5 */nums/* 6 */// 7 /* 8*/// 9 /* 10 *//* 11 */ let a /* 12 */ = /* 13 */ n1 + n1/* 14*//* 15 */ let b /*16*/ = /*17*/ n1 * n1/*18*///19 select (a /* 12 */ , b /*16*/ )/*22*//*23*/) { /*20*/ Console.WriteLine(a + b);//21 } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); // No linq refactoring offered due to variable declaration(s) in outermost foreach. await TestActionCountAsync(source, count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsDefault_02() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|/* 1 */ foreach /* 2 */(int /* 3 */ n1 /* 4 */in /* 5 */ nums /* 6 */)// 7 /* 8*/{// 9 /* 10 */ if /* 11 */ (/* 12 */ n1 /* 13 */ > /* 14 */ 0/* 15 */ ) // 16 /* 17 */{ // 18 /*19*/Console.WriteLine(n1);//20 /* 21 */} // 22 /*23*/}/*24*/|] } }"; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var n1 /* 4 */in /* 17 */// 18 /* 1 */from/* 2 */int /* 3 */ n1 /* 4 */in/* 5 */nums/* 6 */// 7 /* 8*/// 9 /* 10 */ where/* 11 *//* 12 */n1 /* 13 */ > /* 14 */ 0/* 15 */// 16 select n1/* 4 *//* 21 */// 22 /*23*//*24*/ ) { /*19*/ Console.WriteLine(n1);//20 } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var n1 /* 4 */in nums /* 6 */.Where( /* 10 *//* 11 *//* 8*/// 9 n1 => /* 12 */n1 /* 13 */ > /* 14 */ 0/* 15 */// 16 ) /* 1 *//* 2 *//* 17 */// 18 /* 3 *//* 4 *//* 4 *//* 21 */// 22 /*23*//*24*//* 5 */// 7 ) { /*19*/ Console.WriteLine(n1);//20 } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } #endregion #region Preprocessor directives [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task NoConversionPreprocessorDirectives() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|foreach(var x in nums) { #if (true) yield return x + 1; #endif }|] } }"; // Cannot convert expressions with preprocessor directives await TestMissingAsync(source); } #endregion } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictingIdentifierTracker.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; namespace Microsoft.CodeAnalysis.Rename.ConflictEngine { internal sealed class ConflictingIdentifierTracker { /// <summary> /// The core data structure of the tracker. This is a dictionary of variable name to the /// current identifier tokens that are declaring variables. This should only ever be updated /// via the AddIdentifier and RemoveIdentifier helpers. /// </summary> private readonly Dictionary<string, List<SyntaxToken>> _currentIdentifiersInScope; private readonly HashSet<SyntaxToken> _conflictingTokensToReport; private readonly SyntaxToken _tokenBeingRenamed; public ConflictingIdentifierTracker(SyntaxToken tokenBeingRenamed, IEqualityComparer<string> identifierComparer) { _currentIdentifiersInScope = new Dictionary<string, List<SyntaxToken>>(identifierComparer); _conflictingTokensToReport = new HashSet<SyntaxToken>(); _tokenBeingRenamed = tokenBeingRenamed; } public IEnumerable<SyntaxToken> ConflictingTokens => _conflictingTokensToReport; public void AddIdentifier(SyntaxToken token) { if (token.IsMissing || token.ValueText == null) { return; } var name = token.ValueText; if (_currentIdentifiersInScope.TryGetValue(name, out var conflictingTokens)) { conflictingTokens.Add(token); // If at least one of the identifiers is the one we're renaming, // track it. This means that conflicts unrelated to our rename (that // were there when we started) we won't flag. if (conflictingTokens.Contains(_tokenBeingRenamed)) { foreach (var conflictingToken in conflictingTokens) { if (conflictingToken != _tokenBeingRenamed) { // conflictingTokensToReport is a set, so we won't get duplicates _conflictingTokensToReport.Add(conflictingToken); } } } } else { // No identifiers yet, so record the first one _currentIdentifiersInScope.Add(name, new List<SyntaxToken> { token }); } } public void AddIdentifiers(IEnumerable<SyntaxToken> tokens) { foreach (var token in tokens) { AddIdentifier(token); } } public void RemoveIdentifier(SyntaxToken token) { if (token.IsMissing || token.ValueText == null) { return; } var name = token.ValueText; var currentIdentifiers = _currentIdentifiersInScope[name]; currentIdentifiers.Remove(token); if (currentIdentifiers.Count == 0) { _currentIdentifiersInScope.Remove(name); } } public void RemoveIdentifiers(IEnumerable<SyntaxToken> tokens) { foreach (var token in tokens) { RemoveIdentifier(token); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Rename.ConflictEngine { internal sealed class ConflictingIdentifierTracker { /// <summary> /// The core data structure of the tracker. This is a dictionary of variable name to the /// current identifier tokens that are declaring variables. This should only ever be updated /// via the AddIdentifier and RemoveIdentifier helpers. /// </summary> private readonly Dictionary<string, List<SyntaxToken>> _currentIdentifiersInScope; private readonly HashSet<SyntaxToken> _conflictingTokensToReport; private readonly SyntaxToken _tokenBeingRenamed; public ConflictingIdentifierTracker(SyntaxToken tokenBeingRenamed, IEqualityComparer<string> identifierComparer) { _currentIdentifiersInScope = new Dictionary<string, List<SyntaxToken>>(identifierComparer); _conflictingTokensToReport = new HashSet<SyntaxToken>(); _tokenBeingRenamed = tokenBeingRenamed; } public IEnumerable<SyntaxToken> ConflictingTokens => _conflictingTokensToReport; public void AddIdentifier(SyntaxToken token) { if (token.IsMissing || token.ValueText == null) { return; } var name = token.ValueText; if (_currentIdentifiersInScope.TryGetValue(name, out var conflictingTokens)) { conflictingTokens.Add(token); // If at least one of the identifiers is the one we're renaming, // track it. This means that conflicts unrelated to our rename (that // were there when we started) we won't flag. if (conflictingTokens.Contains(_tokenBeingRenamed)) { foreach (var conflictingToken in conflictingTokens) { if (conflictingToken != _tokenBeingRenamed) { // conflictingTokensToReport is a set, so we won't get duplicates _conflictingTokensToReport.Add(conflictingToken); } } } } else { // No identifiers yet, so record the first one _currentIdentifiersInScope.Add(name, new List<SyntaxToken> { token }); } } public void AddIdentifiers(IEnumerable<SyntaxToken> tokens) { foreach (var token in tokens) { AddIdentifier(token); } } public void RemoveIdentifier(SyntaxToken token) { if (token.IsMissing || token.ValueText == null) { return; } var name = token.ValueText; var currentIdentifiers = _currentIdentifiersInScope[name]; currentIdentifiers.Remove(token); if (currentIdentifiers.Count == 0) { _currentIdentifiersInScope.Remove(name); } } public void RemoveIdentifiers(IEnumerable<SyntaxToken> tokens) { foreach (var token in tokens) { RemoveIdentifier(token); } } } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/CSharpCodeFixVerifier`2.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Testing; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Testing; using Microsoft.CodeAnalysis.Testing.Verifiers; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public static partial class CSharpCodeFixVerifier<TAnalyzer, TCodeFix> where TAnalyzer : DiagnosticAnalyzer, new() where TCodeFix : CodeFixProvider, new() { /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.Diagnostic()"/> public static DiagnosticResult Diagnostic() => CSharpCodeFixVerifier<TAnalyzer, TCodeFix, XUnitVerifier>.Diagnostic(); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.Diagnostic(string)"/> public static DiagnosticResult Diagnostic(string diagnosticId) => CSharpCodeFixVerifier<TAnalyzer, TCodeFix, XUnitVerifier>.Diagnostic(diagnosticId); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.Diagnostic(DiagnosticDescriptor)"/> public static DiagnosticResult Diagnostic(DiagnosticDescriptor descriptor) => CSharpCodeFixVerifier<TAnalyzer, TCodeFix, XUnitVerifier>.Diagnostic(descriptor); /// <summary> /// Verify standard properties of <typeparamref name="TAnalyzer"/>. /// </summary> /// <remarks> /// This validation method is largely specific to dotnet/roslyn scenarios. /// </remarks> public static void VerifyStandardProperty(AnalyzerProperty property) => CodeFixVerifierHelper.VerifyStandardProperty(new TAnalyzer(), property); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyAnalyzerAsync(string, DiagnosticResult[])"/> public static async Task VerifyAnalyzerAsync(string source, params DiagnosticResult[] expected) { var test = new Test { TestCode = source, }; test.ExpectedDiagnostics.AddRange(expected); await test.RunAsync(); } /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, string)"/> public static async Task VerifyCodeFixAsync(string source, string fixedSource) => await VerifyCodeFixAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, DiagnosticResult, string)"/> public static async Task VerifyCodeFixAsync(string source, DiagnosticResult expected, string fixedSource) => await VerifyCodeFixAsync(source, new[] { expected }, fixedSource); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, DiagnosticResult[], string)"/> public static async Task VerifyCodeFixAsync(string source, DiagnosticResult[] expected, string fixedSource) { var test = new Test { TestCode = source, FixedCode = fixedSource, }; test.ExpectedDiagnostics.AddRange(expected); await test.RunAsync(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Testing; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Testing; using Microsoft.CodeAnalysis.Testing.Verifiers; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public static partial class CSharpCodeFixVerifier<TAnalyzer, TCodeFix> where TAnalyzer : DiagnosticAnalyzer, new() where TCodeFix : CodeFixProvider, new() { /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.Diagnostic()"/> public static DiagnosticResult Diagnostic() => CSharpCodeFixVerifier<TAnalyzer, TCodeFix, XUnitVerifier>.Diagnostic(); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.Diagnostic(string)"/> public static DiagnosticResult Diagnostic(string diagnosticId) => CSharpCodeFixVerifier<TAnalyzer, TCodeFix, XUnitVerifier>.Diagnostic(diagnosticId); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.Diagnostic(DiagnosticDescriptor)"/> public static DiagnosticResult Diagnostic(DiagnosticDescriptor descriptor) => CSharpCodeFixVerifier<TAnalyzer, TCodeFix, XUnitVerifier>.Diagnostic(descriptor); /// <summary> /// Verify standard properties of <typeparamref name="TAnalyzer"/>. /// </summary> /// <remarks> /// This validation method is largely specific to dotnet/roslyn scenarios. /// </remarks> public static void VerifyStandardProperty(AnalyzerProperty property) => CodeFixVerifierHelper.VerifyStandardProperty(new TAnalyzer(), property); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyAnalyzerAsync(string, DiagnosticResult[])"/> public static async Task VerifyAnalyzerAsync(string source, params DiagnosticResult[] expected) { var test = new Test { TestCode = source, }; test.ExpectedDiagnostics.AddRange(expected); await test.RunAsync(); } /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, string)"/> public static async Task VerifyCodeFixAsync(string source, string fixedSource) => await VerifyCodeFixAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, DiagnosticResult, string)"/> public static async Task VerifyCodeFixAsync(string source, DiagnosticResult expected, string fixedSource) => await VerifyCodeFixAsync(source, new[] { expected }, fixedSource); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, DiagnosticResult[], string)"/> public static async Task VerifyCodeFixAsync(string source, DiagnosticResult[] expected, string fixedSource) { var test = new Test { TestCode = source, FixedCode = fixedSource, }; test.ExpectedDiagnostics.AddRange(expected); await test.RunAsync(); } } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/Features/Core/Portable/ImplementInterface/AbstractImplementInterfaceService.State.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.Threading; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.ImplementInterface { internal abstract partial class AbstractImplementInterfaceService { internal class State { public SyntaxNode Location { get; } public SyntaxNode ClassOrStructDecl { get; } public INamedTypeSymbol ClassOrStructType { get; } public IEnumerable<INamedTypeSymbol> InterfaceTypes { get; } public SemanticModel Model { get; } // The members that are not implemented at all. public ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented { get; private set; } = ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; public ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> MembersWithoutExplicitOrImplicitImplementation { get; private set; } = ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; // The members that have no explicit implementation. public ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> MembersWithoutExplicitImplementation { get; private set; } = ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; public State(SyntaxNode interfaceNode, SyntaxNode classOrStructDecl, INamedTypeSymbol classOrStructType, IEnumerable<INamedTypeSymbol> interfaceTypes, SemanticModel model) { Location = interfaceNode; ClassOrStructDecl = classOrStructDecl; ClassOrStructType = classOrStructType; InterfaceTypes = interfaceTypes; Model = model; } public static State Generate( AbstractImplementInterfaceService service, Document document, SemanticModel model, SyntaxNode interfaceNode, CancellationToken cancellationToken) { if (!service.TryInitializeState(document, model, interfaceNode, cancellationToken, out var classOrStructDecl, out var classOrStructType, out var interfaceTypes)) { return null; } if (!CodeGenerator.CanAdd(document.Project.Solution, classOrStructType, cancellationToken)) { return null; } var state = new State(interfaceNode, classOrStructDecl, classOrStructType, interfaceTypes, model); if (service.CanImplementImplicitly) { state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented = state.ClassOrStructType.GetAllUnimplementedMembers( interfaceTypes, includeMembersRequiringExplicitImplementation: false, cancellationToken); state.MembersWithoutExplicitOrImplicitImplementation = state.ClassOrStructType.GetAllUnimplementedMembers( interfaceTypes, includeMembersRequiringExplicitImplementation: true, cancellationToken); state.MembersWithoutExplicitImplementation = state.ClassOrStructType.GetAllUnimplementedExplicitMembers( interfaceTypes, cancellationToken); var allMembersImplemented = state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented.Length == 0; var allMembersImplementedExplicitly = state.MembersWithoutExplicitImplementation.Length == 0; return !allMembersImplementedExplicitly || !allMembersImplemented ? state : null; } else { // We put the members in this bucket so that the code fix title is "Implement Interface" state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented = state.ClassOrStructType.GetAllUnimplementedExplicitMembers( interfaceTypes, cancellationToken); var allMembersImplemented = state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented.Length == 0; return !allMembersImplemented ? state : 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.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.ImplementInterface { internal abstract partial class AbstractImplementInterfaceService { internal class State { public SyntaxNode Location { get; } public SyntaxNode ClassOrStructDecl { get; } public INamedTypeSymbol ClassOrStructType { get; } public IEnumerable<INamedTypeSymbol> InterfaceTypes { get; } public SemanticModel Model { get; } // The members that are not implemented at all. public ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented { get; private set; } = ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; public ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> MembersWithoutExplicitOrImplicitImplementation { get; private set; } = ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; // The members that have no explicit implementation. public ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> MembersWithoutExplicitImplementation { get; private set; } = ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; public State(SyntaxNode interfaceNode, SyntaxNode classOrStructDecl, INamedTypeSymbol classOrStructType, IEnumerable<INamedTypeSymbol> interfaceTypes, SemanticModel model) { Location = interfaceNode; ClassOrStructDecl = classOrStructDecl; ClassOrStructType = classOrStructType; InterfaceTypes = interfaceTypes; Model = model; } public static State Generate( AbstractImplementInterfaceService service, Document document, SemanticModel model, SyntaxNode interfaceNode, CancellationToken cancellationToken) { if (!service.TryInitializeState(document, model, interfaceNode, cancellationToken, out var classOrStructDecl, out var classOrStructType, out var interfaceTypes)) { return null; } if (!CodeGenerator.CanAdd(document.Project.Solution, classOrStructType, cancellationToken)) { return null; } var state = new State(interfaceNode, classOrStructDecl, classOrStructType, interfaceTypes, model); if (service.CanImplementImplicitly) { state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented = state.ClassOrStructType.GetAllUnimplementedMembers( interfaceTypes, includeMembersRequiringExplicitImplementation: false, cancellationToken); state.MembersWithoutExplicitOrImplicitImplementation = state.ClassOrStructType.GetAllUnimplementedMembers( interfaceTypes, includeMembersRequiringExplicitImplementation: true, cancellationToken); state.MembersWithoutExplicitImplementation = state.ClassOrStructType.GetAllUnimplementedExplicitMembers( interfaceTypes, cancellationToken); var allMembersImplemented = state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented.Length == 0; var allMembersImplementedExplicitly = state.MembersWithoutExplicitImplementation.Length == 0; return !allMembersImplementedExplicitly || !allMembersImplemented ? state : null; } else { // We put the members in this bucket so that the code fix title is "Implement Interface" state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented = state.ClassOrStructType.GetAllUnimplementedExplicitMembers( interfaceTypes, cancellationToken); var allMembersImplemented = state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented.Length == 0; return !allMembersImplemented ? state : null; } } } } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/EditorFeatures/Core/Implementation/AutomaticCompletion/AbstractAutomaticLineEnderCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion { internal abstract class AbstractAutomaticLineEnderCommandHandler : IChainedCommandHandler<AutomaticLineEnderCommandArgs> { private readonly ITextUndoHistoryRegistry _undoRegistry; private readonly IEditorOperationsFactoryService _editorOperationsFactoryService; public string DisplayName => EditorFeaturesResources.Automatic_Line_Ender; protected AbstractAutomaticLineEnderCommandHandler( ITextUndoHistoryRegistry undoRegistry, IEditorOperationsFactoryService editorOperationsFactoryService) { _undoRegistry = undoRegistry; _editorOperationsFactoryService = editorOperationsFactoryService; } /// <summary> /// get ending string if there is one /// </summary> protected abstract string? GetEndingString(Document document, int position, CancellationToken cancellationToken); /// <summary> /// do next action /// </summary> protected abstract void NextAction(IEditorOperations editorOperation, Action nextAction); /// <summary> /// format after inserting ending string /// </summary> protected abstract Document FormatAndApplyBasedOnEndToken(Document document, int position, CancellationToken cancellationToken); /// <summary> /// special cases where we do not want to do line completion but just fall back to line break and formatting. /// </summary> protected abstract bool TreatAsReturn(Document document, int caretPosition, CancellationToken cancellationToken); /// <summary> /// Add or remove the braces for <param name="selectedNode"/>. /// </summary> protected abstract void ModifySelectedNode(AutomaticLineEnderCommandArgs args, Document document, SyntaxNode selectedNode, bool addBrace, int caretPosition, CancellationToken cancellationToken); /// <summary> /// Get the syntax node needs add/remove braces. /// </summary> protected abstract (SyntaxNode selectedNode, bool addBrace)? GetValidNodeToModifyBraces(Document document, int caretPosition, CancellationToken cancellationToken); public CommandState GetCommandState(AutomaticLineEnderCommandArgs args, Func<CommandState> nextHandler) => CommandState.Available; public void ExecuteCommand(AutomaticLineEnderCommandArgs args, Action nextHandler, CommandExecutionContext context) { // get editor operation var operations = _editorOperationsFactoryService.GetEditorOperations(args.TextView); if (operations == null) { nextHandler(); return; } var document = args.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { NextAction(operations, nextHandler); return; } // feature off if (!document.Project.Solution.Workspace.Options.GetOption(InternalFeatureOnOffOptions.AutomaticLineEnder)) { NextAction(operations, nextHandler); return; } using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Automatically_completing)) { var cancellationToken = context.OperationContext.UserCancellationToken; // caret is not on the subject buffer. nothing we can do var caret = args.TextView.GetCaretPoint(args.SubjectBuffer); if (!caret.HasValue) { NextAction(operations, nextHandler); return; } var caretPosition = caret.Value; // special cases where we treat this command simply as Return. if (TreatAsReturn(document, caretPosition, cancellationToken)) { // leave it to the VS editor to handle this command. // VS editor's default implementation of SmartBreakLine is simply BreakLine, which inserts // a new line and positions the caret with smart indent. nextHandler(); return; } var subjectLineWhereCaretIsOn = caretPosition.GetContainingLine(); // Two possible operations // 1. Add/remove the brace for the selected syntax node (only for C#) // 2. Append an ending string to the line. (For C#, it is semicolon ';', For VB, it is underline '_') // Check if the node could be used to add/remove brace. var selectNodeAndOperationKind = GetValidNodeToModifyBraces(document, caretPosition, cancellationToken); if (selectNodeAndOperationKind != null) { var (selectedNode, addBrace) = selectNodeAndOperationKind.Value; using var transaction = args.TextView.CreateEditTransaction(EditorFeaturesResources.Automatic_Line_Ender, _undoRegistry, _editorOperationsFactoryService); ModifySelectedNode(args, document, selectedNode, addBrace, caretPosition, cancellationToken); NextAction(operations, nextHandler); transaction.Complete(); return; } // Check if we could find the ending position var endingInsertionPosition = GetInsertionPositionForEndingString(document, subjectLineWhereCaretIsOn, cancellationToken); if (endingInsertionPosition != null) { using var transaction = args.TextView.CreateEditTransaction(EditorFeaturesResources.Automatic_Line_Ender, _undoRegistry, _editorOperationsFactoryService); InsertEnding(args.TextView, document, endingInsertionPosition.Value, caretPosition, cancellationToken); NextAction(operations, nextHandler); transaction.Complete(); return; } // Neither of the two operations could be performed using var editTransaction = args.TextView.CreateEditTransaction(EditorFeaturesResources.Automatic_Line_Ender, _undoRegistry, _editorOperationsFactoryService); NextAction(operations, nextHandler); editTransaction.Complete(); } } /// <summary> /// return insertion point for the ending string /// </summary> private static int? GetInsertionPositionForEndingString(Document document, ITextSnapshotLine line, CancellationToken cancellationToken) { var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken); var text = root.SyntaxTree.GetText(cancellationToken); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); // find last token on the line var token = syntaxFacts.FindTokenOnLeftOfPosition(root, line.End); if (token.RawKind == 0) { return null; } // bug # 16770 // don't do anything if token is multiline token such as verbatim string if (line.End < token.Span.End) { return null; } // if there is only whitespace, token doesn't need to be on same line if (string.IsNullOrWhiteSpace(text.ToString(TextSpan.FromBounds(token.Span.End, line.End)))) { return line.End; } // if token is on different line than caret but caret line is empty, we insert ending point at the end of the line if (text.Lines.IndexOf(token.Span.End) != text.Lines.IndexOf(line.End)) { return string.IsNullOrWhiteSpace(line.GetText()) ? (int?)line.End : null; } return token.Span.End; } /// <summary> /// insert ending string if there is one to insert /// </summary> private void InsertEnding( ITextView textView, Document document, int insertPosition, SnapshotPoint caretPosition, CancellationToken cancellationToken) { // 1. Move the caret to line end. textView.TryMoveCaretToAndEnsureVisible(caretPosition.GetContainingLine().End); // 2. Insert ending to the document. var newDocument = document; var endingString = GetEndingString(document, caretPosition, cancellationToken); if (endingString != null) { newDocument = document.InsertText(insertPosition, endingString, cancellationToken); } // 3. format the document and apply the changes to the workspace FormatAndApplyBasedOnEndToken(newDocument, insertPosition, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion { internal abstract class AbstractAutomaticLineEnderCommandHandler : IChainedCommandHandler<AutomaticLineEnderCommandArgs> { private readonly ITextUndoHistoryRegistry _undoRegistry; private readonly IEditorOperationsFactoryService _editorOperationsFactoryService; public string DisplayName => EditorFeaturesResources.Automatic_Line_Ender; protected AbstractAutomaticLineEnderCommandHandler( ITextUndoHistoryRegistry undoRegistry, IEditorOperationsFactoryService editorOperationsFactoryService) { _undoRegistry = undoRegistry; _editorOperationsFactoryService = editorOperationsFactoryService; } /// <summary> /// get ending string if there is one /// </summary> protected abstract string? GetEndingString(Document document, int position, CancellationToken cancellationToken); /// <summary> /// do next action /// </summary> protected abstract void NextAction(IEditorOperations editorOperation, Action nextAction); /// <summary> /// format after inserting ending string /// </summary> protected abstract Document FormatAndApplyBasedOnEndToken(Document document, int position, CancellationToken cancellationToken); /// <summary> /// special cases where we do not want to do line completion but just fall back to line break and formatting. /// </summary> protected abstract bool TreatAsReturn(Document document, int caretPosition, CancellationToken cancellationToken); /// <summary> /// Add or remove the braces for <param name="selectedNode"/>. /// </summary> protected abstract void ModifySelectedNode(AutomaticLineEnderCommandArgs args, Document document, SyntaxNode selectedNode, bool addBrace, int caretPosition, CancellationToken cancellationToken); /// <summary> /// Get the syntax node needs add/remove braces. /// </summary> protected abstract (SyntaxNode selectedNode, bool addBrace)? GetValidNodeToModifyBraces(Document document, int caretPosition, CancellationToken cancellationToken); public CommandState GetCommandState(AutomaticLineEnderCommandArgs args, Func<CommandState> nextHandler) => CommandState.Available; public void ExecuteCommand(AutomaticLineEnderCommandArgs args, Action nextHandler, CommandExecutionContext context) { // get editor operation var operations = _editorOperationsFactoryService.GetEditorOperations(args.TextView); if (operations == null) { nextHandler(); return; } var document = args.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { NextAction(operations, nextHandler); return; } // feature off if (!document.Project.Solution.Workspace.Options.GetOption(InternalFeatureOnOffOptions.AutomaticLineEnder)) { NextAction(operations, nextHandler); return; } using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Automatically_completing)) { var cancellationToken = context.OperationContext.UserCancellationToken; // caret is not on the subject buffer. nothing we can do var caret = args.TextView.GetCaretPoint(args.SubjectBuffer); if (!caret.HasValue) { NextAction(operations, nextHandler); return; } var caretPosition = caret.Value; // special cases where we treat this command simply as Return. if (TreatAsReturn(document, caretPosition, cancellationToken)) { // leave it to the VS editor to handle this command. // VS editor's default implementation of SmartBreakLine is simply BreakLine, which inserts // a new line and positions the caret with smart indent. nextHandler(); return; } var subjectLineWhereCaretIsOn = caretPosition.GetContainingLine(); // Two possible operations // 1. Add/remove the brace for the selected syntax node (only for C#) // 2. Append an ending string to the line. (For C#, it is semicolon ';', For VB, it is underline '_') // Check if the node could be used to add/remove brace. var selectNodeAndOperationKind = GetValidNodeToModifyBraces(document, caretPosition, cancellationToken); if (selectNodeAndOperationKind != null) { var (selectedNode, addBrace) = selectNodeAndOperationKind.Value; using var transaction = args.TextView.CreateEditTransaction(EditorFeaturesResources.Automatic_Line_Ender, _undoRegistry, _editorOperationsFactoryService); ModifySelectedNode(args, document, selectedNode, addBrace, caretPosition, cancellationToken); NextAction(operations, nextHandler); transaction.Complete(); return; } // Check if we could find the ending position var endingInsertionPosition = GetInsertionPositionForEndingString(document, subjectLineWhereCaretIsOn, cancellationToken); if (endingInsertionPosition != null) { using var transaction = args.TextView.CreateEditTransaction(EditorFeaturesResources.Automatic_Line_Ender, _undoRegistry, _editorOperationsFactoryService); InsertEnding(args.TextView, document, endingInsertionPosition.Value, caretPosition, cancellationToken); NextAction(operations, nextHandler); transaction.Complete(); return; } // Neither of the two operations could be performed using var editTransaction = args.TextView.CreateEditTransaction(EditorFeaturesResources.Automatic_Line_Ender, _undoRegistry, _editorOperationsFactoryService); NextAction(operations, nextHandler); editTransaction.Complete(); } } /// <summary> /// return insertion point for the ending string /// </summary> private static int? GetInsertionPositionForEndingString(Document document, ITextSnapshotLine line, CancellationToken cancellationToken) { var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken); var text = root.SyntaxTree.GetText(cancellationToken); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); // find last token on the line var token = syntaxFacts.FindTokenOnLeftOfPosition(root, line.End); if (token.RawKind == 0) { return null; } // bug # 16770 // don't do anything if token is multiline token such as verbatim string if (line.End < token.Span.End) { return null; } // if there is only whitespace, token doesn't need to be on same line if (string.IsNullOrWhiteSpace(text.ToString(TextSpan.FromBounds(token.Span.End, line.End)))) { return line.End; } // if token is on different line than caret but caret line is empty, we insert ending point at the end of the line if (text.Lines.IndexOf(token.Span.End) != text.Lines.IndexOf(line.End)) { return string.IsNullOrWhiteSpace(line.GetText()) ? (int?)line.End : null; } return token.Span.End; } /// <summary> /// insert ending string if there is one to insert /// </summary> private void InsertEnding( ITextView textView, Document document, int insertPosition, SnapshotPoint caretPosition, CancellationToken cancellationToken) { // 1. Move the caret to line end. textView.TryMoveCaretToAndEnsureVisible(caretPosition.GetContainingLine().End); // 2. Insert ending to the document. var newDocument = document; var endingString = GetEndingString(document, caretPosition, cancellationToken); if (endingString != null) { newDocument = document.InsertText(insertPosition, endingString, cancellationToken); } // 3. format the document and apply the changes to the workspace FormatAndApplyBasedOnEndToken(newDocument, insertPosition, cancellationToken); } } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/Features/Core/Portable/CodeCleanup/OrganizeUsingsSettings.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.CodeCleanup { /// <summary> /// Indicates which, if any, Organize Usings features are enabled for code cleanup. /// </summary> internal sealed class OrganizeUsingsSet { public bool IsRemoveUnusedImportEnabled { get; } public bool IsSortImportsEnabled { get; } public OrganizeUsingsSet(bool isRemoveUnusedImportEnabled, bool isSortImportsEnabled) { IsRemoveUnusedImportEnabled = isRemoveUnusedImportEnabled; IsSortImportsEnabled = isSortImportsEnabled; } } }
// Licensed to the .NET Foundation under one or more 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.CodeCleanup { /// <summary> /// Indicates which, if any, Organize Usings features are enabled for code cleanup. /// </summary> internal sealed class OrganizeUsingsSet { public bool IsRemoveUnusedImportEnabled { get; } public bool IsSortImportsEnabled { get; } public OrganizeUsingsSet(bool isRemoveUnusedImportEnabled, bool isSortImportsEnabled) { IsRemoveUnusedImportEnabled = isRemoveUnusedImportEnabled; IsSortImportsEnabled = isSortImportsEnabled; } } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/EditorFeatures/Core/GoToDefinition/AbstractGoToDefinitionService.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.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.GoToDefinition; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.GoToDefinition { // GoToDefinition internal abstract class AbstractGoToDefinitionService : AbstractFindDefinitionService, IGoToDefinitionService { private readonly IThreadingContext _threadingContext; /// <summary> /// Used to present go to definition results in <see cref="TryGoToDefinition(Document, int, CancellationToken)"/> /// </summary> private readonly IStreamingFindUsagesPresenter _streamingPresenter; protected AbstractGoToDefinitionService( IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingPresenter) { _threadingContext = threadingContext; _streamingPresenter = streamingPresenter; } async Task<IEnumerable<INavigableItem>?> IGoToDefinitionService.FindDefinitionsAsync(Document document, int position, CancellationToken cancellationToken) => await FindDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false); private static bool TryNavigateToSpan(Document document, int position, CancellationToken cancellationToken) { var solution = document.Project.Solution; var workspace = solution.Workspace; var service = workspace.Services.GetRequiredService<IDocumentNavigationService>(); var options = solution.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true); options = options.WithChangedOption(NavigationOptions.ActivateTab, true); return service.TryNavigateToPosition(workspace, document.Id, position, virtualSpace: 0, options, cancellationToken); } public bool TryGoToDefinition(Document document, int position, CancellationToken cancellationToken) { var symbolService = document.GetRequiredLanguageService<IGoToDefinitionSymbolService>(); var targetPositionOfControlFlow = symbolService.GetTargetIfControlFlowAsync(document, position, cancellationToken).WaitAndGetResult(cancellationToken); if (targetPositionOfControlFlow is not null) { return TryNavigateToSpan(document, targetPositionOfControlFlow.Value, cancellationToken); } // Try to compute the referenced symbol and attempt to go to definition for the symbol. var (symbol, _) = symbolService.GetSymbolAndBoundSpanAsync(document, position, includeType: true, cancellationToken).WaitAndGetResult(cancellationToken); if (symbol is null) return false; // if the symbol only has a single source location, and we're already on it, // try to see if there's a better symbol we could navigate to. var remapped = TryGoToAlternativeLocationIfAlreadyOnDefinition(document, position, symbol, cancellationToken); if (remapped) return true; var isThirdPartyNavigationAllowed = IsThirdPartyNavigationAllowed(symbol, position, document, cancellationToken); return GoToDefinitionHelpers.TryGoToDefinition( symbol, document.Project.Solution, _threadingContext, _streamingPresenter, thirdPartyNavigationAllowed: isThirdPartyNavigationAllowed, cancellationToken: cancellationToken); } private bool TryGoToAlternativeLocationIfAlreadyOnDefinition( Document document, int position, ISymbol symbol, CancellationToken cancellationToken) { var project = document.Project; var solution = project.Solution; var sourceLocations = symbol.Locations.WhereAsArray(loc => loc.IsInSource); if (sourceLocations.Length != 1) return false; var definitionLocation = sourceLocations[0]; if (!definitionLocation.SourceSpan.IntersectsWith(position)) return false; var definitionTree = definitionLocation.SourceTree; var definitionDocument = solution.GetDocument(definitionTree); if (definitionDocument != document) return false; // Ok, we were already on the definition. Look for better symbols we could show results // for instead. For now, just see if we're on an interface member impl. If so, we can // instead navigate to the actual interface member. // // In the future we can expand this with other mappings if appropriate. var interfaceImpls = symbol.ExplicitOrImplicitInterfaceImplementations(); if (interfaceImpls.Length == 0) return false; var definitions = interfaceImpls.SelectMany( i => GoToDefinitionHelpers.GetDefinitions( i, solution, thirdPartyNavigationAllowed: false, cancellationToken)).ToImmutableArray(); var title = string.Format(EditorFeaturesResources._0_implemented_members, FindUsagesHelpers.GetDisplayName(symbol)); return _threadingContext.JoinableTaskFactory.Run(() => _streamingPresenter.TryNavigateToOrPresentItemsAsync( _threadingContext, solution.Workspace, title, definitions, cancellationToken)); } private static bool IsThirdPartyNavigationAllowed(ISymbol symbolToNavigateTo, int caretPosition, Document document, CancellationToken cancellationToken) { var syntaxRoot = document.GetSyntaxRootSynchronously(cancellationToken); var syntaxFactsService = document.GetRequiredLanguageService<ISyntaxFactsService>(); var containingTypeDeclaration = syntaxFactsService.GetContainingTypeDeclaration(syntaxRoot, caretPosition); if (containingTypeDeclaration != null) { var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); Debug.Assert(semanticModel != null); // Allow third parties to navigate to all symbols except types/constructors // if we are navigating from the corresponding type. if (semanticModel.GetDeclaredSymbol(containingTypeDeclaration, cancellationToken) is ITypeSymbol containingTypeSymbol && (symbolToNavigateTo is ITypeSymbol || symbolToNavigateTo.IsConstructor())) { var candidateTypeSymbol = symbolToNavigateTo is ITypeSymbol ? symbolToNavigateTo : symbolToNavigateTo.ContainingType; if (Equals(containingTypeSymbol, candidateTypeSymbol)) { // We are navigating from the same type, so don't allow third parties to perform the navigation. // This ensures that if we navigate to a class from within that class, we'll stay in the same file // rather than navigate to, say, XAML. return false; } } } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.GoToDefinition; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.GoToDefinition { // GoToDefinition internal abstract class AbstractGoToDefinitionService : AbstractFindDefinitionService, IGoToDefinitionService { private readonly IThreadingContext _threadingContext; /// <summary> /// Used to present go to definition results in <see cref="TryGoToDefinition(Document, int, CancellationToken)"/> /// </summary> private readonly IStreamingFindUsagesPresenter _streamingPresenter; protected AbstractGoToDefinitionService( IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingPresenter) { _threadingContext = threadingContext; _streamingPresenter = streamingPresenter; } async Task<IEnumerable<INavigableItem>?> IGoToDefinitionService.FindDefinitionsAsync(Document document, int position, CancellationToken cancellationToken) => await FindDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false); private static bool TryNavigateToSpan(Document document, int position, CancellationToken cancellationToken) { var solution = document.Project.Solution; var workspace = solution.Workspace; var service = workspace.Services.GetRequiredService<IDocumentNavigationService>(); var options = solution.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true); options = options.WithChangedOption(NavigationOptions.ActivateTab, true); return service.TryNavigateToPosition(workspace, document.Id, position, virtualSpace: 0, options, cancellationToken); } public bool TryGoToDefinition(Document document, int position, CancellationToken cancellationToken) { var symbolService = document.GetRequiredLanguageService<IGoToDefinitionSymbolService>(); var targetPositionOfControlFlow = symbolService.GetTargetIfControlFlowAsync(document, position, cancellationToken).WaitAndGetResult(cancellationToken); if (targetPositionOfControlFlow is not null) { return TryNavigateToSpan(document, targetPositionOfControlFlow.Value, cancellationToken); } // Try to compute the referenced symbol and attempt to go to definition for the symbol. var (symbol, _) = symbolService.GetSymbolAndBoundSpanAsync(document, position, includeType: true, cancellationToken).WaitAndGetResult(cancellationToken); if (symbol is null) return false; // if the symbol only has a single source location, and we're already on it, // try to see if there's a better symbol we could navigate to. var remapped = TryGoToAlternativeLocationIfAlreadyOnDefinition(document, position, symbol, cancellationToken); if (remapped) return true; var isThirdPartyNavigationAllowed = IsThirdPartyNavigationAllowed(symbol, position, document, cancellationToken); return GoToDefinitionHelpers.TryGoToDefinition( symbol, document.Project.Solution, _threadingContext, _streamingPresenter, thirdPartyNavigationAllowed: isThirdPartyNavigationAllowed, cancellationToken: cancellationToken); } private bool TryGoToAlternativeLocationIfAlreadyOnDefinition( Document document, int position, ISymbol symbol, CancellationToken cancellationToken) { var project = document.Project; var solution = project.Solution; var sourceLocations = symbol.Locations.WhereAsArray(loc => loc.IsInSource); if (sourceLocations.Length != 1) return false; var definitionLocation = sourceLocations[0]; if (!definitionLocation.SourceSpan.IntersectsWith(position)) return false; var definitionTree = definitionLocation.SourceTree; var definitionDocument = solution.GetDocument(definitionTree); if (definitionDocument != document) return false; // Ok, we were already on the definition. Look for better symbols we could show results // for instead. For now, just see if we're on an interface member impl. If so, we can // instead navigate to the actual interface member. // // In the future we can expand this with other mappings if appropriate. var interfaceImpls = symbol.ExplicitOrImplicitInterfaceImplementations(); if (interfaceImpls.Length == 0) return false; var definitions = interfaceImpls.SelectMany( i => GoToDefinitionHelpers.GetDefinitions( i, solution, thirdPartyNavigationAllowed: false, cancellationToken)).ToImmutableArray(); var title = string.Format(EditorFeaturesResources._0_implemented_members, FindUsagesHelpers.GetDisplayName(symbol)); return _threadingContext.JoinableTaskFactory.Run(() => _streamingPresenter.TryNavigateToOrPresentItemsAsync( _threadingContext, solution.Workspace, title, definitions, cancellationToken)); } private static bool IsThirdPartyNavigationAllowed(ISymbol symbolToNavigateTo, int caretPosition, Document document, CancellationToken cancellationToken) { var syntaxRoot = document.GetSyntaxRootSynchronously(cancellationToken); var syntaxFactsService = document.GetRequiredLanguageService<ISyntaxFactsService>(); var containingTypeDeclaration = syntaxFactsService.GetContainingTypeDeclaration(syntaxRoot, caretPosition); if (containingTypeDeclaration != null) { var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); Debug.Assert(semanticModel != null); // Allow third parties to navigate to all symbols except types/constructors // if we are navigating from the corresponding type. if (semanticModel.GetDeclaredSymbol(containingTypeDeclaration, cancellationToken) is ITypeSymbol containingTypeSymbol && (symbolToNavigateTo is ITypeSymbol || symbolToNavigateTo.IsConstructor())) { var candidateTypeSymbol = symbolToNavigateTo is ITypeSymbol ? symbolToNavigateTo : symbolToNavigateTo.ContainingType; if (Equals(containingTypeSymbol, candidateTypeSymbol)) { // We are navigating from the same type, so don't allow third parties to perform the navigation. // This ensures that if we navigate to a class from within that class, we'll stay in the same file // rather than navigate to, say, XAML. return false; } } } return true; } } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/VisualStudio/Core/Impl/Options/Style/NamingPreferences/SymbolSpecification/SymbolSpecificationViewModel.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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences { internal class SymbolSpecificationViewModel : AbstractNotifyPropertyChanged, INamingStylesInfoDialogViewModel { public Guid ID { get; set; } public List<SymbolKindViewModel> SymbolKindList { get; set; } public List<AccessibilityViewModel> AccessibilityList { get; set; } public List<ModifierViewModel> ModifierList { get; set; } private string _symbolSpecName; public bool CanBeDeleted { get; set; } private readonly INotificationService _notificationService; public SymbolSpecificationViewModel( string languageName, bool canBeDeleted, INotificationService notificationService) : this(languageName, CreateDefaultSymbolSpecification(), canBeDeleted, notificationService) { } public SymbolSpecificationViewModel(string languageName, SymbolSpecification specification, bool canBeDeleted, INotificationService notificationService) { CanBeDeleted = canBeDeleted; _notificationService = notificationService; ItemName = specification.Name; ID = specification.ID; // The list of supported SymbolKinds is limited due to https://github.com/dotnet/roslyn/issues/8753. if (languageName == LanguageNames.CSharp) { SymbolKindList = new List<SymbolKindViewModel> { new SymbolKindViewModel(SymbolKind.Namespace, ServicesVSResources.NamingSpecification_CSharp_Namespace, specification), new SymbolKindViewModel(TypeKind.Class, ServicesVSResources.NamingSpecification_CSharp_Class, specification), new SymbolKindViewModel(TypeKind.Struct, ServicesVSResources.NamingSpecification_CSharp_Struct, specification), new SymbolKindViewModel(TypeKind.Interface, ServicesVSResources.NamingSpecification_CSharp_Interface, specification), new SymbolKindViewModel(TypeKind.Enum, ServicesVSResources.NamingSpecification_CSharp_Enum, specification), new SymbolKindViewModel(SymbolKind.Property, ServicesVSResources.NamingSpecification_CSharp_Property, specification), new SymbolKindViewModel(MethodKind.Ordinary, ServicesVSResources.NamingSpecification_CSharp_Method, specification), new SymbolKindViewModel(MethodKind.LocalFunction, ServicesVSResources.NamingSpecification_CSharp_LocalFunction, specification), new SymbolKindViewModel(SymbolKind.Field, ServicesVSResources.NamingSpecification_CSharp_Field, specification), new SymbolKindViewModel(SymbolKind.Event, ServicesVSResources.NamingSpecification_CSharp_Event, specification), new SymbolKindViewModel(TypeKind.Delegate, ServicesVSResources.NamingSpecification_CSharp_Delegate, specification), new SymbolKindViewModel(SymbolKind.Parameter, ServicesVSResources.NamingSpecification_CSharp_Parameter, specification), new SymbolKindViewModel(SymbolKind.TypeParameter, ServicesVSResources.NamingSpecification_CSharp_TypeParameter, specification), new SymbolKindViewModel(SymbolKind.Local, ServicesVSResources.NamingSpecification_CSharp_Local, specification) }; // Not localized because they're language keywords AccessibilityList = new List<AccessibilityViewModel> { new AccessibilityViewModel(Accessibility.Public, "public", specification), new AccessibilityViewModel(Accessibility.Internal, "internal", specification), new AccessibilityViewModel(Accessibility.Private, "private", specification), new AccessibilityViewModel(Accessibility.Protected, "protected", specification), new AccessibilityViewModel(Accessibility.ProtectedOrInternal, "protected internal", specification), new AccessibilityViewModel(Accessibility.ProtectedAndInternal, "private protected", specification), new AccessibilityViewModel(Accessibility.NotApplicable, "local", specification), }; // Not localized because they're language keywords ModifierList = new List<ModifierViewModel> { new ModifierViewModel(DeclarationModifiers.Abstract, "abstract", specification), new ModifierViewModel(DeclarationModifiers.Async, "async", specification), new ModifierViewModel(DeclarationModifiers.Const, "const", specification), new ModifierViewModel(DeclarationModifiers.ReadOnly, "readonly", specification), new ModifierViewModel(DeclarationModifiers.Static, "static", specification) }; } else if (languageName == LanguageNames.VisualBasic) { SymbolKindList = new List<SymbolKindViewModel> { new SymbolKindViewModel(SymbolKind.Namespace, ServicesVSResources.NamingSpecification_VisualBasic_Namespace, specification), new SymbolKindViewModel(TypeKind.Class, ServicesVSResources.NamingSpecification_VisualBasic_Class, specification), new SymbolKindViewModel(TypeKind.Struct, ServicesVSResources.NamingSpecification_VisualBasic_Structure, specification), new SymbolKindViewModel(TypeKind.Interface, ServicesVSResources.NamingSpecification_VisualBasic_Interface, specification), new SymbolKindViewModel(TypeKind.Enum, ServicesVSResources.NamingSpecification_VisualBasic_Enum, specification), new SymbolKindViewModel(TypeKind.Module, ServicesVSResources.NamingSpecification_VisualBasic_Module, specification), new SymbolKindViewModel(SymbolKind.Property, ServicesVSResources.NamingSpecification_VisualBasic_Property, specification), new SymbolKindViewModel(SymbolKind.Method, ServicesVSResources.NamingSpecification_VisualBasic_Method, specification), new SymbolKindViewModel(SymbolKind.Field, ServicesVSResources.NamingSpecification_VisualBasic_Field, specification), new SymbolKindViewModel(SymbolKind.Event, ServicesVSResources.NamingSpecification_VisualBasic_Event, specification), new SymbolKindViewModel(TypeKind.Delegate, ServicesVSResources.NamingSpecification_VisualBasic_Delegate, specification), new SymbolKindViewModel(SymbolKind.Parameter, ServicesVSResources.NamingSpecification_VisualBasic_Parameter, specification), new SymbolKindViewModel(SymbolKind.TypeParameter, ServicesVSResources.NamingSpecification_VisualBasic_TypeParameter, specification), new SymbolKindViewModel(SymbolKind.Local, ServicesVSResources.NamingSpecification_VisualBasic_Local, specification) }; // Not localized because they're language keywords AccessibilityList = new List<AccessibilityViewModel> { new AccessibilityViewModel(Accessibility.Public, "Public", specification), new AccessibilityViewModel(Accessibility.Friend, "Friend", specification), new AccessibilityViewModel(Accessibility.Private, "Private", specification), new AccessibilityViewModel(Accessibility.Protected , "Protected", specification), new AccessibilityViewModel(Accessibility.ProtectedOrInternal, "Protected Friend", specification), new AccessibilityViewModel(Accessibility.ProtectedAndInternal, "Private Protected", specification), new AccessibilityViewModel(Accessibility.NotApplicable, "Local", specification), }; // Not localized because they're language keywords ModifierList = new List<ModifierViewModel> { new ModifierViewModel(DeclarationModifiers.Abstract, "MustInherit", specification), new ModifierViewModel(DeclarationModifiers.Async, "Async", specification), new ModifierViewModel(DeclarationModifiers.Const, "Const", specification), new ModifierViewModel(DeclarationModifiers.ReadOnly, "ReadOnly", specification), new ModifierViewModel(DeclarationModifiers.Static, "Shared", specification) }; } else { throw new ArgumentException(string.Format("Unexpected language name: {0}", languageName), nameof(languageName)); } } public string ItemName { get { return _symbolSpecName; } set { SetProperty(ref _symbolSpecName, value); } } internal SymbolSpecification GetSymbolSpecification() { return new SymbolSpecification( ID, ItemName, SymbolKindList.Where(s => s.IsChecked).Select(s => s.CreateSymbolOrTypeOrMethodKind()).ToImmutableArray(), AccessibilityList.Where(a => a.IsChecked).Select(a => a._accessibility).ToImmutableArray(), ModifierList.Where(m => m.IsChecked).Select(m => new ModifierKind(m._modifier)).ToImmutableArray()); } internal bool TrySubmit() { if (string.IsNullOrWhiteSpace(ItemName)) { _notificationService.SendNotification(ServicesVSResources.Enter_a_title_for_this_Naming_Style); return false; } return true; } // For screen readers public override string ToString() => _symbolSpecName; internal interface ISymbolSpecificationViewModelPart { bool IsChecked { get; set; } } public class SymbolKindViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { public string Name { get; set; } public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } private readonly SymbolKind? _symbolKind; private readonly TypeKind? _typeKind; private readonly MethodKind? _methodKind; private bool _isChecked; public SymbolKindViewModel(SymbolKind symbolKind, string name, SymbolSpecification specification) { _symbolKind = symbolKind; Name = name; IsChecked = specification.ApplicableSymbolKindList.Any(k => k.SymbolKind == symbolKind); } public SymbolKindViewModel(TypeKind typeKind, string name, SymbolSpecification specification) { _typeKind = typeKind; Name = name; IsChecked = specification.ApplicableSymbolKindList.Any(k => k.TypeKind == typeKind); } public SymbolKindViewModel(MethodKind methodKind, string name, SymbolSpecification specification) { _methodKind = methodKind; Name = name; IsChecked = specification.ApplicableSymbolKindList.Any(k => k.MethodKind == methodKind); } internal SymbolKindOrTypeKind CreateSymbolOrTypeOrMethodKind() { return _symbolKind.HasValue ? new SymbolKindOrTypeKind(_symbolKind.Value) : _typeKind.HasValue ? new SymbolKindOrTypeKind(_typeKind.Value) : _methodKind.HasValue ? new SymbolKindOrTypeKind(_methodKind.Value) : throw ExceptionUtilities.Unreachable; } } public class AccessibilityViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { internal readonly Accessibility _accessibility; public string Name { get; set; } private bool _isChecked; public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } public AccessibilityViewModel(Accessibility accessibility, string name, SymbolSpecification specification) { _accessibility = accessibility; Name = name; IsChecked = specification.ApplicableAccessibilityList.Any(a => a == accessibility); } } public class ModifierViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { public string Name { get; set; } private bool _isChecked; public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } internal readonly DeclarationModifiers _modifier; public ModifierViewModel(DeclarationModifiers modifier, string name, SymbolSpecification specification) { _modifier = modifier; Name = name; IsChecked = specification.RequiredModifierList.Any(m => m.Modifier == modifier); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences { internal class SymbolSpecificationViewModel : AbstractNotifyPropertyChanged, INamingStylesInfoDialogViewModel { public Guid ID { get; set; } public List<SymbolKindViewModel> SymbolKindList { get; set; } public List<AccessibilityViewModel> AccessibilityList { get; set; } public List<ModifierViewModel> ModifierList { get; set; } private string _symbolSpecName; public bool CanBeDeleted { get; set; } private readonly INotificationService _notificationService; public SymbolSpecificationViewModel( string languageName, bool canBeDeleted, INotificationService notificationService) : this(languageName, CreateDefaultSymbolSpecification(), canBeDeleted, notificationService) { } public SymbolSpecificationViewModel(string languageName, SymbolSpecification specification, bool canBeDeleted, INotificationService notificationService) { CanBeDeleted = canBeDeleted; _notificationService = notificationService; ItemName = specification.Name; ID = specification.ID; // The list of supported SymbolKinds is limited due to https://github.com/dotnet/roslyn/issues/8753. if (languageName == LanguageNames.CSharp) { SymbolKindList = new List<SymbolKindViewModel> { new SymbolKindViewModel(SymbolKind.Namespace, ServicesVSResources.NamingSpecification_CSharp_Namespace, specification), new SymbolKindViewModel(TypeKind.Class, ServicesVSResources.NamingSpecification_CSharp_Class, specification), new SymbolKindViewModel(TypeKind.Struct, ServicesVSResources.NamingSpecification_CSharp_Struct, specification), new SymbolKindViewModel(TypeKind.Interface, ServicesVSResources.NamingSpecification_CSharp_Interface, specification), new SymbolKindViewModel(TypeKind.Enum, ServicesVSResources.NamingSpecification_CSharp_Enum, specification), new SymbolKindViewModel(SymbolKind.Property, ServicesVSResources.NamingSpecification_CSharp_Property, specification), new SymbolKindViewModel(MethodKind.Ordinary, ServicesVSResources.NamingSpecification_CSharp_Method, specification), new SymbolKindViewModel(MethodKind.LocalFunction, ServicesVSResources.NamingSpecification_CSharp_LocalFunction, specification), new SymbolKindViewModel(SymbolKind.Field, ServicesVSResources.NamingSpecification_CSharp_Field, specification), new SymbolKindViewModel(SymbolKind.Event, ServicesVSResources.NamingSpecification_CSharp_Event, specification), new SymbolKindViewModel(TypeKind.Delegate, ServicesVSResources.NamingSpecification_CSharp_Delegate, specification), new SymbolKindViewModel(SymbolKind.Parameter, ServicesVSResources.NamingSpecification_CSharp_Parameter, specification), new SymbolKindViewModel(SymbolKind.TypeParameter, ServicesVSResources.NamingSpecification_CSharp_TypeParameter, specification), new SymbolKindViewModel(SymbolKind.Local, ServicesVSResources.NamingSpecification_CSharp_Local, specification) }; // Not localized because they're language keywords AccessibilityList = new List<AccessibilityViewModel> { new AccessibilityViewModel(Accessibility.Public, "public", specification), new AccessibilityViewModel(Accessibility.Internal, "internal", specification), new AccessibilityViewModel(Accessibility.Private, "private", specification), new AccessibilityViewModel(Accessibility.Protected, "protected", specification), new AccessibilityViewModel(Accessibility.ProtectedOrInternal, "protected internal", specification), new AccessibilityViewModel(Accessibility.ProtectedAndInternal, "private protected", specification), new AccessibilityViewModel(Accessibility.NotApplicable, "local", specification), }; // Not localized because they're language keywords ModifierList = new List<ModifierViewModel> { new ModifierViewModel(DeclarationModifiers.Abstract, "abstract", specification), new ModifierViewModel(DeclarationModifiers.Async, "async", specification), new ModifierViewModel(DeclarationModifiers.Const, "const", specification), new ModifierViewModel(DeclarationModifiers.ReadOnly, "readonly", specification), new ModifierViewModel(DeclarationModifiers.Static, "static", specification) }; } else if (languageName == LanguageNames.VisualBasic) { SymbolKindList = new List<SymbolKindViewModel> { new SymbolKindViewModel(SymbolKind.Namespace, ServicesVSResources.NamingSpecification_VisualBasic_Namespace, specification), new SymbolKindViewModel(TypeKind.Class, ServicesVSResources.NamingSpecification_VisualBasic_Class, specification), new SymbolKindViewModel(TypeKind.Struct, ServicesVSResources.NamingSpecification_VisualBasic_Structure, specification), new SymbolKindViewModel(TypeKind.Interface, ServicesVSResources.NamingSpecification_VisualBasic_Interface, specification), new SymbolKindViewModel(TypeKind.Enum, ServicesVSResources.NamingSpecification_VisualBasic_Enum, specification), new SymbolKindViewModel(TypeKind.Module, ServicesVSResources.NamingSpecification_VisualBasic_Module, specification), new SymbolKindViewModel(SymbolKind.Property, ServicesVSResources.NamingSpecification_VisualBasic_Property, specification), new SymbolKindViewModel(SymbolKind.Method, ServicesVSResources.NamingSpecification_VisualBasic_Method, specification), new SymbolKindViewModel(SymbolKind.Field, ServicesVSResources.NamingSpecification_VisualBasic_Field, specification), new SymbolKindViewModel(SymbolKind.Event, ServicesVSResources.NamingSpecification_VisualBasic_Event, specification), new SymbolKindViewModel(TypeKind.Delegate, ServicesVSResources.NamingSpecification_VisualBasic_Delegate, specification), new SymbolKindViewModel(SymbolKind.Parameter, ServicesVSResources.NamingSpecification_VisualBasic_Parameter, specification), new SymbolKindViewModel(SymbolKind.TypeParameter, ServicesVSResources.NamingSpecification_VisualBasic_TypeParameter, specification), new SymbolKindViewModel(SymbolKind.Local, ServicesVSResources.NamingSpecification_VisualBasic_Local, specification) }; // Not localized because they're language keywords AccessibilityList = new List<AccessibilityViewModel> { new AccessibilityViewModel(Accessibility.Public, "Public", specification), new AccessibilityViewModel(Accessibility.Friend, "Friend", specification), new AccessibilityViewModel(Accessibility.Private, "Private", specification), new AccessibilityViewModel(Accessibility.Protected , "Protected", specification), new AccessibilityViewModel(Accessibility.ProtectedOrInternal, "Protected Friend", specification), new AccessibilityViewModel(Accessibility.ProtectedAndInternal, "Private Protected", specification), new AccessibilityViewModel(Accessibility.NotApplicable, "Local", specification), }; // Not localized because they're language keywords ModifierList = new List<ModifierViewModel> { new ModifierViewModel(DeclarationModifiers.Abstract, "MustInherit", specification), new ModifierViewModel(DeclarationModifiers.Async, "Async", specification), new ModifierViewModel(DeclarationModifiers.Const, "Const", specification), new ModifierViewModel(DeclarationModifiers.ReadOnly, "ReadOnly", specification), new ModifierViewModel(DeclarationModifiers.Static, "Shared", specification) }; } else { throw new ArgumentException(string.Format("Unexpected language name: {0}", languageName), nameof(languageName)); } } public string ItemName { get { return _symbolSpecName; } set { SetProperty(ref _symbolSpecName, value); } } internal SymbolSpecification GetSymbolSpecification() { return new SymbolSpecification( ID, ItemName, SymbolKindList.Where(s => s.IsChecked).Select(s => s.CreateSymbolOrTypeOrMethodKind()).ToImmutableArray(), AccessibilityList.Where(a => a.IsChecked).Select(a => a._accessibility).ToImmutableArray(), ModifierList.Where(m => m.IsChecked).Select(m => new ModifierKind(m._modifier)).ToImmutableArray()); } internal bool TrySubmit() { if (string.IsNullOrWhiteSpace(ItemName)) { _notificationService.SendNotification(ServicesVSResources.Enter_a_title_for_this_Naming_Style); return false; } return true; } // For screen readers public override string ToString() => _symbolSpecName; internal interface ISymbolSpecificationViewModelPart { bool IsChecked { get; set; } } public class SymbolKindViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { public string Name { get; set; } public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } private readonly SymbolKind? _symbolKind; private readonly TypeKind? _typeKind; private readonly MethodKind? _methodKind; private bool _isChecked; public SymbolKindViewModel(SymbolKind symbolKind, string name, SymbolSpecification specification) { _symbolKind = symbolKind; Name = name; IsChecked = specification.ApplicableSymbolKindList.Any(k => k.SymbolKind == symbolKind); } public SymbolKindViewModel(TypeKind typeKind, string name, SymbolSpecification specification) { _typeKind = typeKind; Name = name; IsChecked = specification.ApplicableSymbolKindList.Any(k => k.TypeKind == typeKind); } public SymbolKindViewModel(MethodKind methodKind, string name, SymbolSpecification specification) { _methodKind = methodKind; Name = name; IsChecked = specification.ApplicableSymbolKindList.Any(k => k.MethodKind == methodKind); } internal SymbolKindOrTypeKind CreateSymbolOrTypeOrMethodKind() { return _symbolKind.HasValue ? new SymbolKindOrTypeKind(_symbolKind.Value) : _typeKind.HasValue ? new SymbolKindOrTypeKind(_typeKind.Value) : _methodKind.HasValue ? new SymbolKindOrTypeKind(_methodKind.Value) : throw ExceptionUtilities.Unreachable; } } public class AccessibilityViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { internal readonly Accessibility _accessibility; public string Name { get; set; } private bool _isChecked; public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } public AccessibilityViewModel(Accessibility accessibility, string name, SymbolSpecification specification) { _accessibility = accessibility; Name = name; IsChecked = specification.ApplicableAccessibilityList.Any(a => a == accessibility); } } public class ModifierViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { public string Name { get; set; } private bool _isChecked; public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } internal readonly DeclarationModifiers _modifier; public ModifierViewModel(DeclarationModifiers modifier, string name, SymbolSpecification specification) { _modifier = modifier; Name = name; IsChecked = specification.RequiredModifierList.Any(m => m.Modifier == modifier); } } } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/Features/Core/Portable/ExtractMethod/AbstractExtractMethodService.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 System.Threading.Tasks; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract class AbstractExtractMethodService<TValidator, TExtractor, TResult> : IExtractMethodService where TValidator : SelectionValidator where TExtractor : MethodExtractor where TResult : SelectionResult { protected abstract TValidator CreateSelectionValidator(SemanticDocument document, TextSpan textSpan, OptionSet options); protected abstract TExtractor CreateMethodExtractor(TResult selectionResult, bool localFunction); public async Task<ExtractMethodResult> ExtractMethodAsync( Document document, TextSpan textSpan, bool localFunction, OptionSet options, CancellationToken cancellationToken) { options ??= await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false); var validator = CreateSelectionValidator(semanticDocument, textSpan, options); var selectionResult = await validator.GetValidSelectionAsync(cancellationToken).ConfigureAwait(false); if (!selectionResult.ContainsValidContext) { return new FailedExtractMethodResult(selectionResult.Status); } cancellationToken.ThrowIfCancellationRequested(); // extract method var extractor = CreateMethodExtractor((TResult)selectionResult, localFunction); return await extractor.ExtractMethodAsync(cancellationToken).ConfigureAwait(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract class AbstractExtractMethodService<TValidator, TExtractor, TResult> : IExtractMethodService where TValidator : SelectionValidator where TExtractor : MethodExtractor where TResult : SelectionResult { protected abstract TValidator CreateSelectionValidator(SemanticDocument document, TextSpan textSpan, OptionSet options); protected abstract TExtractor CreateMethodExtractor(TResult selectionResult, bool localFunction); public async Task<ExtractMethodResult> ExtractMethodAsync( Document document, TextSpan textSpan, bool localFunction, OptionSet options, CancellationToken cancellationToken) { options ??= await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false); var validator = CreateSelectionValidator(semanticDocument, textSpan, options); var selectionResult = await validator.GetValidSelectionAsync(cancellationToken).ConfigureAwait(false); if (!selectionResult.ContainsValidContext) { return new FailedExtractMethodResult(selectionResult.Status); } cancellationToken.ThrowIfCancellationRequested(); // extract method var extractor = CreateMethodExtractor((TResult)selectionResult, localFunction); return await extractor.ExtractMethodAsync(cancellationToken).ConfigureAwait(false); } } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/VisualStudio/Core/Def/Implementation/ContainedLanguageRefactorNotifyService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation { using Workspace = Microsoft.CodeAnalysis.Workspace; [Export(typeof(IRefactorNotifyService))] internal sealed class ContainedLanguageRefactorNotifyService : IRefactorNotifyService { private static readonly SymbolDisplayFormat s_qualifiedDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ContainedLanguageRefactorNotifyService() { } public bool TryOnBeforeGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, ISymbol symbol, string newName, bool throwOnFailure) => true; public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, ISymbol symbol, string newName, bool throwOnFailure) { if (workspace is VisualStudioWorkspaceImpl visualStudioWorkspace) { foreach (var documentId in changedDocumentIDs) { var containedDocument = visualStudioWorkspace.TryGetContainedDocument(documentId); if (containedDocument != null) { var containedLanguageHost = containedDocument.ContainedLanguageHost; if (containedLanguageHost != null) { var hresult = containedLanguageHost.OnRenamed( GetRenameType(symbol), symbol.ToDisplayString(s_qualifiedDisplayFormat), newName); if (hresult < 0) { if (throwOnFailure) { Marshal.ThrowExceptionForHR(hresult); } else { return false; } } } } } } return true; } private ContainedLanguageRenameType GetRenameType(ISymbol symbol) { if (symbol is INamespaceSymbol) { return ContainedLanguageRenameType.CLRT_NAMESPACE; } else if (symbol is INamedTypeSymbol && (symbol as INamedTypeSymbol).TypeKind == TypeKind.Class) { return ContainedLanguageRenameType.CLRT_CLASS; } else if (symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Field || symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Property) { return ContainedLanguageRenameType.CLRT_CLASSMEMBER; } else { return ContainedLanguageRenameType.CLRT_OTHER; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation { using Workspace = Microsoft.CodeAnalysis.Workspace; [Export(typeof(IRefactorNotifyService))] internal sealed class ContainedLanguageRefactorNotifyService : IRefactorNotifyService { private static readonly SymbolDisplayFormat s_qualifiedDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ContainedLanguageRefactorNotifyService() { } public bool TryOnBeforeGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, ISymbol symbol, string newName, bool throwOnFailure) => true; public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, ISymbol symbol, string newName, bool throwOnFailure) { if (workspace is VisualStudioWorkspaceImpl visualStudioWorkspace) { foreach (var documentId in changedDocumentIDs) { var containedDocument = visualStudioWorkspace.TryGetContainedDocument(documentId); if (containedDocument != null) { var containedLanguageHost = containedDocument.ContainedLanguageHost; if (containedLanguageHost != null) { var hresult = containedLanguageHost.OnRenamed( GetRenameType(symbol), symbol.ToDisplayString(s_qualifiedDisplayFormat), newName); if (hresult < 0) { if (throwOnFailure) { Marshal.ThrowExceptionForHR(hresult); } else { return false; } } } } } } return true; } private ContainedLanguageRenameType GetRenameType(ISymbol symbol) { if (symbol is INamespaceSymbol) { return ContainedLanguageRenameType.CLRT_NAMESPACE; } else if (symbol is INamedTypeSymbol && (symbol as INamedTypeSymbol).TypeKind == TypeKind.Class) { return ContainedLanguageRenameType.CLRT_CLASS; } else if (symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Field || symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Property) { return ContainedLanguageRenameType.CLRT_CLASSMEMBER; } else { return ContainedLanguageRenameType.CLRT_OTHER; } } } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/Features/Core/Portable/SolutionCrawler/SolutionCrawlerService.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.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal partial class SolutionCrawlerRegistrationService : ISolutionCrawlerRegistrationService { /// <summary> /// nested class of <see cref="SolutionCrawlerRegistrationService"/> since it is tightly coupled with it. /// /// <see cref="ISolutionCrawlerService"/> is implemented by this class since WorkspaceService doesn't allow a class to implement /// more than one <see cref="IWorkspaceService"/>. /// </summary> [ExportWorkspaceService(typeof(ISolutionCrawlerService), ServiceLayer.Default), Shared] internal class SolutionCrawlerService : ISolutionCrawlerService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SolutionCrawlerService() { } public void Reanalyze(Workspace workspace, IIncrementalAnalyzer analyzer, IEnumerable<ProjectId>? projectIds = null, IEnumerable<DocumentId>? documentIds = null, bool highPriority = false) { // if solution crawler doesn't exist for the given workspace. don't do anything if (workspace.Services.GetService<ISolutionCrawlerRegistrationService>() is SolutionCrawlerRegistrationService registration) { registration.Reanalyze(workspace, analyzer, projectIds, documentIds, highPriority); } } public ISolutionCrawlerProgressReporter GetProgressReporter(Workspace workspace) { // if solution crawler doesn't exist for the given workspace, return null reporter if (workspace.Services.GetService<ISolutionCrawlerRegistrationService>() is SolutionCrawlerRegistrationService registration) { // currently we have only 1 global reporter that are shared by all workspaces. return registration._progressReporter; } return NullReporter.Instance; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal partial class SolutionCrawlerRegistrationService : ISolutionCrawlerRegistrationService { /// <summary> /// nested class of <see cref="SolutionCrawlerRegistrationService"/> since it is tightly coupled with it. /// /// <see cref="ISolutionCrawlerService"/> is implemented by this class since WorkspaceService doesn't allow a class to implement /// more than one <see cref="IWorkspaceService"/>. /// </summary> [ExportWorkspaceService(typeof(ISolutionCrawlerService), ServiceLayer.Default), Shared] internal class SolutionCrawlerService : ISolutionCrawlerService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SolutionCrawlerService() { } public void Reanalyze(Workspace workspace, IIncrementalAnalyzer analyzer, IEnumerable<ProjectId>? projectIds = null, IEnumerable<DocumentId>? documentIds = null, bool highPriority = false) { // if solution crawler doesn't exist for the given workspace. don't do anything if (workspace.Services.GetService<ISolutionCrawlerRegistrationService>() is SolutionCrawlerRegistrationService registration) { registration.Reanalyze(workspace, analyzer, projectIds, documentIds, highPriority); } } public ISolutionCrawlerProgressReporter GetProgressReporter(Workspace workspace) { // if solution crawler doesn't exist for the given workspace, return null reporter if (workspace.Services.GetService<ISolutionCrawlerRegistrationService>() is SolutionCrawlerRegistrationService registration) { // currently we have only 1 global reporter that are shared by all workspaces. return registration._progressReporter; } return NullReporter.Instance; } } } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/Workspaces/Core/Portable/Options/OptionSet+AnalyzerConfigOptionsImpl.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.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Options { public abstract partial class OptionSet { private sealed class AnalyzerConfigOptionsImpl : AnalyzerConfigOptions { private readonly OptionSet _optionSet; private readonly IOptionService _optionService; private readonly string? _language; public AnalyzerConfigOptionsImpl(OptionSet optionSet, IOptionService optionService, string? language) { _optionSet = optionSet; _optionService = optionService; _language = language; } public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value) { if (!_optionService.TryMapEditorConfigKeyToOption(key, _language, out var storageLocation, out var optionKey)) { // There are couple of reasons this assert might fire: // 1. Attempting to access an option which does not have an IEditorConfigStorageLocation. // 2. Attempting to access an option which is not exposed from any option provider, i.e. IOptionProvider.Options. Debug.Fail("Failed to find an .editorconfig entry for the requested key."); value = null; return false; } var typedValue = _optionSet.GetOption(optionKey); value = storageLocation.GetEditorConfigStringValue(typedValue, _optionSet); return true; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Options { public abstract partial class OptionSet { private sealed class AnalyzerConfigOptionsImpl : AnalyzerConfigOptions { private readonly OptionSet _optionSet; private readonly IOptionService _optionService; private readonly string? _language; public AnalyzerConfigOptionsImpl(OptionSet optionSet, IOptionService optionService, string? language) { _optionSet = optionSet; _optionService = optionService; _language = language; } public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value) { if (!_optionService.TryMapEditorConfigKeyToOption(key, _language, out var storageLocation, out var optionKey)) { // There are couple of reasons this assert might fire: // 1. Attempting to access an option which does not have an IEditorConfigStorageLocation. // 2. Attempting to access an option which is not exposed from any option provider, i.e. IOptionProvider.Options. Debug.Fail("Failed to find an .editorconfig entry for the requested key."); value = null; return false; } var typedValue = _optionSet.GetOption(optionKey); value = storageLocation.GetEditorConfigStringValue(typedValue, _optionSet); return true; } } } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/Compilers/Core/Portable/SourceGeneration/Nodes/IIncrementalGeneratorNode.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.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a node in the execution pipeline of an incremental generator /// </summary> /// <typeparam name="T">The type of value this step operates on</typeparam> internal interface IIncrementalGeneratorNode<T> { NodeStateTable<T> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<T> previousTable, CancellationToken cancellationToken); IIncrementalGeneratorNode<T> WithComparer(IEqualityComparer<T> comparer); void RegisterOutput(IIncrementalGeneratorOutputNode output); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a node in the execution pipeline of an incremental generator /// </summary> /// <typeparam name="T">The type of value this step operates on</typeparam> internal interface IIncrementalGeneratorNode<T> { NodeStateTable<T> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<T> previousTable, CancellationToken cancellationToken); IIncrementalGeneratorNode<T> WithComparer(IEqualityComparer<T> comparer); void RegisterOutput(IIncrementalGeneratorOutputNode output); } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/Compilers/CSharp/Test/Symbol/Symbols/Source/TypeMapTests.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.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class TypeMapTests : CSharpTestBase { // take a type of the form Something<X> and return the type X. private TypeSymbol TypeArg(TypeSymbol t) { var nts = t as NamedTypeSymbol; Assert.NotNull(nts); Assert.Equal(1, nts.Arity); return nts.TypeArguments()[0]; } [Fact] public void TestMap1() { var text = @" public class Box<T> {} public class A<T> { public class TBox : Box<T> {} public class B<U> { public class TBox : Box<T> {} public class UBox : Box<U> {} public class C { public class TBox : Box<T> {} public class UBox : Box<U> {} } } } public class E {} public class F {} public class Top : A<E> { // base is A<E> public class BF : B<F> {} // base is A<E>.B<F> } "; var comp = CreateEmptyCompilation(text); var global = comp.GlobalNamespace; var at = global.GetTypeMembers("A", 1).Single(); // A<T> var t = at.TypeParameters[0]; Assert.Equal(t, TypeArg(at.GetTypeMembers("TBox", 0).Single().BaseType())); var atbu = at.GetTypeMembers("B", 1).Single(); // A<T>.B<U> var u = atbu.TypeParameters[0]; var c = atbu.GetTypeMembers("C", 0).Single(); // A<T>.B<U>.C Assert.Equal(atbu, c.ContainingType); Assert.Equal(u, TypeArg(c.ContainingType)); Assert.Equal(at, c.ContainingType.ContainingType); Assert.Equal(t, TypeArg(c.ContainingType.ContainingType)); var e = global.GetTypeMembers("E", 0).Single(); // E var f = global.GetTypeMembers("F", 0).Single(); // F var top = global.GetTypeMembers("Top", 0).Single(); // Top var ae = top.BaseType(); // A<E> Assert.Equal(at, ae.OriginalDefinition); Assert.Equal(at, at.ConstructedFrom); Assert.Equal(e, TypeArg(ae)); var bf = top.GetTypeMembers("BF", 0).Single(); // Top.BF Assert.Equal(top, bf.ContainingType); var aebf = bf.BaseType(); Assert.Equal(f, TypeArg(aebf)); Assert.Equal(ae, aebf.ContainingType); var aebfc = aebf.GetTypeMembers("C", 0).Single(); // A<E>.B<F>.C Assert.Equal(c, aebfc.OriginalDefinition); Assert.NotEqual(c, aebfc.ConstructedFrom); Assert.Equal(f, TypeArg(aebfc.ContainingType)); Assert.Equal(e, TypeArg(aebfc.ContainingType.ContainingType)); Assert.Equal(e, TypeArg(aebfc.GetTypeMembers("TBox", 0).Single().BaseType())); Assert.Equal(f, TypeArg(aebfc.GetTypeMembers("UBox", 0).Single().BaseType())); // exercises alpha-renaming. Assert.Equal(aebfc, DeepConstruct(c, ImmutableArray.Create<TypeSymbol>(e, f))); // exercise DeepConstruct } /// <summary> /// Returns a constructed type given the type it is constructed from and type arguments for its enclosing types and itself. /// </summary> /// <param name="typeArguments">the type arguments that will replace the type parameters, starting with those for enclosing types</param> /// <returns></returns> private static NamedTypeSymbol DeepConstruct(NamedTypeSymbol type, ImmutableArray<TypeSymbol> typeArguments) { Assert.True(type.IsDefinition); var allTypeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); type.GetAllTypeParameters(allTypeParameters); return new TypeMap(allTypeParameters.ToImmutableAndFree(), typeArguments.SelectAsArray(t => TypeWithAnnotations.Create(t))).SubstituteNamedType(type); } [Fact] public void ConstructedError() { var text = @" class C { NonExistentType<int> field; } "; var tree = Parse(text); var comp = CreateCompilation(tree); var global = comp.GlobalNamespace; var c = global.GetTypeMembers("C", 0).Single() as NamedTypeSymbol; var field = c.GetMembers("field").Single() as FieldSymbol; var neti = field.Type as NamedTypeSymbol; Assert.Equal(SpecialType.System_Int32, neti.TypeArguments()[0].SpecialType); } [Fact] public void Generics4() { string source = @" class C1<C1T1, C1T2> { public class C2<C2T1, C2T2> { public class C3<C3T1, C3T2> { public C1<int, C3T2>.C2<byte, C3T2>.C3<char, C3T2> V1; } } } "; var compilation = CreateCompilation(source); var _int = compilation.GetSpecialType(SpecialType.System_Int32); var _byte = compilation.GetSpecialType(SpecialType.System_Byte); var _char = compilation.GetSpecialType(SpecialType.System_Char); var C1 = compilation.GetTypeByMetadataName("C1`2"); var c1OfByteChar = C1.Construct(_byte, _char); Assert.Equal("C1<System.Byte, System.Char>", c1OfByteChar.ToTestDisplayString()); var c1OfByteChar_c2 = (NamedTypeSymbol)(c1OfByteChar.GetMembers()[0]); var c1OfByteChar_c2OfIntInt = c1OfByteChar_c2.Construct(_int, _int); Assert.Equal("C1<System.Byte, System.Char>.C2<System.Int32, System.Int32>", c1OfByteChar_c2OfIntInt.ToTestDisplayString()); var c1OfByteChar_c2OfIntInt_c3 = (NamedTypeSymbol)(c1OfByteChar_c2OfIntInt.GetMembers()[0]); var c1OfByteChar_c2OfIntInt_c3OfIntByte = c1OfByteChar_c2OfIntInt_c3.Construct(_int, _byte); Assert.Equal("C1<System.Byte, System.Char>.C2<System.Int32, System.Int32>.C3<System.Int32, System.Byte>", c1OfByteChar_c2OfIntInt_c3OfIntByte.ToTestDisplayString()); var v1 = c1OfByteChar_c2OfIntInt_c3OfIntByte.GetMembers().OfType<FieldSymbol>().First(); var type = v1.TypeWithAnnotations; Assert.Equal("C1<System.Int32, System.Byte>.C2<System.Byte, System.Byte>.C3<System.Char, System.Byte>", type.Type.ToTestDisplayString()); } [Fact] public void Generics5() { string source = @" class C1<C1T1, C1T2> { public class C2<C2T1, C2T2> { public class C3<C3T1, C3T2> { public C1<int, C3T2>.C2<byte, C3T2>.C3<char, C3T2> V1; } } } "; var compilation = CreateCompilation(source); var _int = compilation.GetSpecialType(SpecialType.System_Int32); var _byte = compilation.GetSpecialType(SpecialType.System_Byte); var _char = compilation.GetSpecialType(SpecialType.System_Char); var C1 = compilation.GetTypeByMetadataName("C1`2"); var c1OfByteChar = C1.Construct(_byte, _char); Assert.Equal("C1<System.Byte, System.Char>", c1OfByteChar.ToTestDisplayString()); var c1OfByteChar_c2 = (NamedTypeSymbol)(c1OfByteChar.GetMembers()[0]); Assert.Throws<ArgumentException>(() => { var c1OfByteChar_c2OfIntInt = c1OfByteChar_c2.Construct(_byte, _char, _int, _int); }); } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class TypeMapTests : CSharpTestBase { // take a type of the form Something<X> and return the type X. private TypeSymbol TypeArg(TypeSymbol t) { var nts = t as NamedTypeSymbol; Assert.NotNull(nts); Assert.Equal(1, nts.Arity); return nts.TypeArguments()[0]; } [Fact] public void TestMap1() { var text = @" public class Box<T> {} public class A<T> { public class TBox : Box<T> {} public class B<U> { public class TBox : Box<T> {} public class UBox : Box<U> {} public class C { public class TBox : Box<T> {} public class UBox : Box<U> {} } } } public class E {} public class F {} public class Top : A<E> { // base is A<E> public class BF : B<F> {} // base is A<E>.B<F> } "; var comp = CreateEmptyCompilation(text); var global = comp.GlobalNamespace; var at = global.GetTypeMembers("A", 1).Single(); // A<T> var t = at.TypeParameters[0]; Assert.Equal(t, TypeArg(at.GetTypeMembers("TBox", 0).Single().BaseType())); var atbu = at.GetTypeMembers("B", 1).Single(); // A<T>.B<U> var u = atbu.TypeParameters[0]; var c = atbu.GetTypeMembers("C", 0).Single(); // A<T>.B<U>.C Assert.Equal(atbu, c.ContainingType); Assert.Equal(u, TypeArg(c.ContainingType)); Assert.Equal(at, c.ContainingType.ContainingType); Assert.Equal(t, TypeArg(c.ContainingType.ContainingType)); var e = global.GetTypeMembers("E", 0).Single(); // E var f = global.GetTypeMembers("F", 0).Single(); // F var top = global.GetTypeMembers("Top", 0).Single(); // Top var ae = top.BaseType(); // A<E> Assert.Equal(at, ae.OriginalDefinition); Assert.Equal(at, at.ConstructedFrom); Assert.Equal(e, TypeArg(ae)); var bf = top.GetTypeMembers("BF", 0).Single(); // Top.BF Assert.Equal(top, bf.ContainingType); var aebf = bf.BaseType(); Assert.Equal(f, TypeArg(aebf)); Assert.Equal(ae, aebf.ContainingType); var aebfc = aebf.GetTypeMembers("C", 0).Single(); // A<E>.B<F>.C Assert.Equal(c, aebfc.OriginalDefinition); Assert.NotEqual(c, aebfc.ConstructedFrom); Assert.Equal(f, TypeArg(aebfc.ContainingType)); Assert.Equal(e, TypeArg(aebfc.ContainingType.ContainingType)); Assert.Equal(e, TypeArg(aebfc.GetTypeMembers("TBox", 0).Single().BaseType())); Assert.Equal(f, TypeArg(aebfc.GetTypeMembers("UBox", 0).Single().BaseType())); // exercises alpha-renaming. Assert.Equal(aebfc, DeepConstruct(c, ImmutableArray.Create<TypeSymbol>(e, f))); // exercise DeepConstruct } /// <summary> /// Returns a constructed type given the type it is constructed from and type arguments for its enclosing types and itself. /// </summary> /// <param name="typeArguments">the type arguments that will replace the type parameters, starting with those for enclosing types</param> /// <returns></returns> private static NamedTypeSymbol DeepConstruct(NamedTypeSymbol type, ImmutableArray<TypeSymbol> typeArguments) { Assert.True(type.IsDefinition); var allTypeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); type.GetAllTypeParameters(allTypeParameters); return new TypeMap(allTypeParameters.ToImmutableAndFree(), typeArguments.SelectAsArray(t => TypeWithAnnotations.Create(t))).SubstituteNamedType(type); } [Fact] public void ConstructedError() { var text = @" class C { NonExistentType<int> field; } "; var tree = Parse(text); var comp = CreateCompilation(tree); var global = comp.GlobalNamespace; var c = global.GetTypeMembers("C", 0).Single() as NamedTypeSymbol; var field = c.GetMembers("field").Single() as FieldSymbol; var neti = field.Type as NamedTypeSymbol; Assert.Equal(SpecialType.System_Int32, neti.TypeArguments()[0].SpecialType); } [Fact] public void Generics4() { string source = @" class C1<C1T1, C1T2> { public class C2<C2T1, C2T2> { public class C3<C3T1, C3T2> { public C1<int, C3T2>.C2<byte, C3T2>.C3<char, C3T2> V1; } } } "; var compilation = CreateCompilation(source); var _int = compilation.GetSpecialType(SpecialType.System_Int32); var _byte = compilation.GetSpecialType(SpecialType.System_Byte); var _char = compilation.GetSpecialType(SpecialType.System_Char); var C1 = compilation.GetTypeByMetadataName("C1`2"); var c1OfByteChar = C1.Construct(_byte, _char); Assert.Equal("C1<System.Byte, System.Char>", c1OfByteChar.ToTestDisplayString()); var c1OfByteChar_c2 = (NamedTypeSymbol)(c1OfByteChar.GetMembers()[0]); var c1OfByteChar_c2OfIntInt = c1OfByteChar_c2.Construct(_int, _int); Assert.Equal("C1<System.Byte, System.Char>.C2<System.Int32, System.Int32>", c1OfByteChar_c2OfIntInt.ToTestDisplayString()); var c1OfByteChar_c2OfIntInt_c3 = (NamedTypeSymbol)(c1OfByteChar_c2OfIntInt.GetMembers()[0]); var c1OfByteChar_c2OfIntInt_c3OfIntByte = c1OfByteChar_c2OfIntInt_c3.Construct(_int, _byte); Assert.Equal("C1<System.Byte, System.Char>.C2<System.Int32, System.Int32>.C3<System.Int32, System.Byte>", c1OfByteChar_c2OfIntInt_c3OfIntByte.ToTestDisplayString()); var v1 = c1OfByteChar_c2OfIntInt_c3OfIntByte.GetMembers().OfType<FieldSymbol>().First(); var type = v1.TypeWithAnnotations; Assert.Equal("C1<System.Int32, System.Byte>.C2<System.Byte, System.Byte>.C3<System.Char, System.Byte>", type.Type.ToTestDisplayString()); } [Fact] public void Generics5() { string source = @" class C1<C1T1, C1T2> { public class C2<C2T1, C2T2> { public class C3<C3T1, C3T2> { public C1<int, C3T2>.C2<byte, C3T2>.C3<char, C3T2> V1; } } } "; var compilation = CreateCompilation(source); var _int = compilation.GetSpecialType(SpecialType.System_Int32); var _byte = compilation.GetSpecialType(SpecialType.System_Byte); var _char = compilation.GetSpecialType(SpecialType.System_Char); var C1 = compilation.GetTypeByMetadataName("C1`2"); var c1OfByteChar = C1.Construct(_byte, _char); Assert.Equal("C1<System.Byte, System.Char>", c1OfByteChar.ToTestDisplayString()); var c1OfByteChar_c2 = (NamedTypeSymbol)(c1OfByteChar.GetMembers()[0]); Assert.Throws<ArgumentException>(() => { var c1OfByteChar_c2OfIntInt = c1OfByteChar_c2.Construct(_byte, _char, _int, _int); }); } } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/VisualStudio/CSharp/Impl/Options/AutomationObject/AutomationObject.Formatting.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Formatting; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { public partial class AutomationObject { public int Indent_BlockContents { get { return GetBooleanOption(CSharpFormattingOptions2.IndentBlock); } set { SetBooleanOption(CSharpFormattingOptions2.IndentBlock, value); } } public int Indent_Braces { get { return GetBooleanOption(CSharpFormattingOptions2.IndentBraces); } set { SetBooleanOption(CSharpFormattingOptions2.IndentBraces, value); } } public int Indent_CaseContents { get { return GetBooleanOption(CSharpFormattingOptions2.IndentSwitchCaseSection); } set { SetBooleanOption(CSharpFormattingOptions2.IndentSwitchCaseSection, value); } } public int Indent_CaseContentsWhenBlock { get { return GetBooleanOption(CSharpFormattingOptions2.IndentSwitchCaseSectionWhenBlock); } set { SetBooleanOption(CSharpFormattingOptions2.IndentSwitchCaseSectionWhenBlock, value); } } public int Indent_CaseLabels { get { return GetBooleanOption(CSharpFormattingOptions2.IndentSwitchSection); } set { SetBooleanOption(CSharpFormattingOptions2.IndentSwitchSection, value); } } public int Indent_FlushLabelsLeft { get { return GetOption(CSharpFormattingOptions2.LabelPositioning) == LabelPositionOptions.LeftMost ? 1 : 0; } set { SetOption(CSharpFormattingOptions2.LabelPositioning, value == 1 ? LabelPositionOptions.LeftMost : LabelPositionOptions.NoIndent); } } public int Indent_UnindentLabels { get { return (int)GetOption(CSharpFormattingOptions2.LabelPositioning); } set { SetOption(CSharpFormattingOptions2.LabelPositioning, (LabelPositionOptions)value); } } public int NewLines_AnonymousTypeInitializer_EachMember { get { return GetBooleanOption(CSharpFormattingOptions2.NewLineForMembersInAnonymousTypes); } set { SetBooleanOption(CSharpFormattingOptions2.NewLineForMembersInAnonymousTypes, value); } } public int NewLines_Braces_AnonymousMethod { get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInAnonymousMethods); } set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInAnonymousMethods, value); } } public int NewLines_Braces_AnonymousTypeInitializer { get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInAnonymousTypes); } set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInAnonymousTypes, value); } } public int NewLines_Braces_ControlFlow { get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInControlBlocks); } set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInControlBlocks, value); } } public int NewLines_Braces_LambdaExpressionBody { get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInLambdaExpressionBody); } set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInLambdaExpressionBody, value); } } public int NewLines_Braces_Method { get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInMethods); } set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInMethods, value); } } public int NewLines_Braces_Property { get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInProperties); } set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInProperties, value); } } public int NewLines_Braces_Accessor { get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInAccessors); } set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInAccessors, value); } } public int NewLines_Braces_ObjectInitializer { get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInObjectCollectionArrayInitializers); } set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInObjectCollectionArrayInitializers, value); } } public int NewLines_Braces_Type { get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInTypes); } set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInTypes, value); } } public int NewLines_Keywords_Catch { get { return GetBooleanOption(CSharpFormattingOptions2.NewLineForCatch); } set { SetBooleanOption(CSharpFormattingOptions2.NewLineForCatch, value); } } public int NewLines_Keywords_Else { get { return GetBooleanOption(CSharpFormattingOptions2.NewLineForElse); } set { SetBooleanOption(CSharpFormattingOptions2.NewLineForElse, value); } } public int NewLines_Keywords_Finally { get { return GetBooleanOption(CSharpFormattingOptions2.NewLineForFinally); } set { SetBooleanOption(CSharpFormattingOptions2.NewLineForFinally, value); } } public int NewLines_ObjectInitializer_EachMember { get { return GetBooleanOption(CSharpFormattingOptions2.NewLineForMembersInObjectInit); } set { SetBooleanOption(CSharpFormattingOptions2.NewLineForMembersInObjectInit, value); } } public int NewLines_QueryExpression_EachClause { get { return GetBooleanOption(CSharpFormattingOptions2.NewLineForClausesInQuery); } set { SetBooleanOption(CSharpFormattingOptions2.NewLineForClausesInQuery, value); } } public int Space_AfterBasesColon { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceAfterColonInBaseTypeDeclaration); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceAfterColonInBaseTypeDeclaration, value); } } public int Space_AfterCast { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceAfterCast); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceAfterCast, value); } } public int Space_AfterComma { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceAfterComma); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceAfterComma, value); } } public int Space_AfterDot { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceAfterDot); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceAfterDot, value); } } public int Space_AfterMethodCallName { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceAfterMethodCallName); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceAfterMethodCallName, value); } } public int Space_AfterMethodDeclarationName { get { return GetBooleanOption(CSharpFormattingOptions2.SpacingAfterMethodDeclarationName); } set { SetBooleanOption(CSharpFormattingOptions2.SpacingAfterMethodDeclarationName, value); } } public int Space_AfterSemicolonsInForStatement { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceAfterSemicolonsInForStatement); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceAfterSemicolonsInForStatement, value); } } public int Space_AroundBinaryOperator { get { return GetOption(CSharpFormattingOptions2.SpacingAroundBinaryOperator) == BinaryOperatorSpacingOptions.Single ? 1 : 0; } set { SetOption(CSharpFormattingOptions2.SpacingAroundBinaryOperator, value == 1 ? BinaryOperatorSpacingOptions.Single : BinaryOperatorSpacingOptions.Ignore); } } public int Space_BeforeBasesColon { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBeforeColonInBaseTypeDeclaration); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceBeforeColonInBaseTypeDeclaration, value); } } public int Space_BeforeComma { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBeforeComma); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceBeforeComma, value); } } public int Space_BeforeDot { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBeforeDot); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceBeforeDot, value); } } public int Space_BeforeOpenSquare { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBeforeOpenSquareBracket); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceBeforeOpenSquareBracket, value); } } public int Space_BeforeSemicolonsInForStatement { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBeforeSemicolonsInForStatement); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceBeforeSemicolonsInForStatement, value); } } public int Space_BetweenEmptyMethodCallParentheses { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBetweenEmptyMethodCallParentheses); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceBetweenEmptyMethodCallParentheses, value); } } public int Space_BetweenEmptyMethodDeclarationParentheses { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBetweenEmptyMethodDeclarationParentheses); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceBetweenEmptyMethodDeclarationParentheses, value); } } public int Space_BetweenEmptySquares { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBetweenEmptySquareBrackets); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceBetweenEmptySquareBrackets, value); } } public int Space_InControlFlowConstruct { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceAfterControlFlowStatementKeyword); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceAfterControlFlowStatementKeyword, value); } } public int Space_WithinCastParentheses { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceWithinCastParentheses); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceWithinCastParentheses, value); } } public int Space_WithinExpressionParentheses { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceWithinExpressionParentheses); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceWithinExpressionParentheses, value); } } public int Space_WithinMethodCallParentheses { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceWithinMethodCallParentheses); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceWithinMethodCallParentheses, value); } } public int Space_WithinMethodDeclarationParentheses { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceWithinMethodDeclarationParenthesis); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceWithinMethodDeclarationParenthesis, value); } } public int Space_WithinOtherParentheses { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceWithinOtherParentheses); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceWithinOtherParentheses, value); } } public int Space_WithinSquares { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceWithinSquareBrackets); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceWithinSquareBrackets, value); } } public int Wrapping_IgnoreSpacesAroundBinaryOperators { get { return (int)GetOption(CSharpFormattingOptions2.SpacingAroundBinaryOperator); } set { SetOption(CSharpFormattingOptions2.SpacingAroundBinaryOperator, (BinaryOperatorSpacingOptions)value); } } public int Wrapping_IgnoreSpacesAroundVariableDeclaration { get { return GetBooleanOption(CSharpFormattingOptions2.SpacesIgnoreAroundVariableDeclaration); } set { SetBooleanOption(CSharpFormattingOptions2.SpacesIgnoreAroundVariableDeclaration, value); } } public int Wrapping_KeepStatementsOnSingleLine { get { return GetBooleanOption(CSharpFormattingOptions2.WrappingKeepStatementsOnSingleLine); } set { SetBooleanOption(CSharpFormattingOptions2.WrappingKeepStatementsOnSingleLine, value); } } public int Wrapping_PreserveSingleLine { get { return GetBooleanOption(CSharpFormattingOptions2.WrappingPreserveSingleLine); } set { SetBooleanOption(CSharpFormattingOptions2.WrappingPreserveSingleLine, value); } } public int Formatting_TriggerOnPaste { get { return GetBooleanOption(FormattingOptions2.FormatOnPaste); } set { SetBooleanOption(FormattingOptions2.FormatOnPaste, value); } } public int Formatting_TriggerOnStatementCompletion { get { return GetBooleanOption(FormattingOptions2.AutoFormattingOnSemicolon); } set { SetBooleanOption(FormattingOptions2.AutoFormattingOnSemicolon, value); } } public int AutoFormattingOnTyping { get { return GetBooleanOption(FormattingOptions2.AutoFormattingOnTyping); } set { SetBooleanOption(FormattingOptions2.AutoFormattingOnTyping, value); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Formatting; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { public partial class AutomationObject { public int Indent_BlockContents { get { return GetBooleanOption(CSharpFormattingOptions2.IndentBlock); } set { SetBooleanOption(CSharpFormattingOptions2.IndentBlock, value); } } public int Indent_Braces { get { return GetBooleanOption(CSharpFormattingOptions2.IndentBraces); } set { SetBooleanOption(CSharpFormattingOptions2.IndentBraces, value); } } public int Indent_CaseContents { get { return GetBooleanOption(CSharpFormattingOptions2.IndentSwitchCaseSection); } set { SetBooleanOption(CSharpFormattingOptions2.IndentSwitchCaseSection, value); } } public int Indent_CaseContentsWhenBlock { get { return GetBooleanOption(CSharpFormattingOptions2.IndentSwitchCaseSectionWhenBlock); } set { SetBooleanOption(CSharpFormattingOptions2.IndentSwitchCaseSectionWhenBlock, value); } } public int Indent_CaseLabels { get { return GetBooleanOption(CSharpFormattingOptions2.IndentSwitchSection); } set { SetBooleanOption(CSharpFormattingOptions2.IndentSwitchSection, value); } } public int Indent_FlushLabelsLeft { get { return GetOption(CSharpFormattingOptions2.LabelPositioning) == LabelPositionOptions.LeftMost ? 1 : 0; } set { SetOption(CSharpFormattingOptions2.LabelPositioning, value == 1 ? LabelPositionOptions.LeftMost : LabelPositionOptions.NoIndent); } } public int Indent_UnindentLabels { get { return (int)GetOption(CSharpFormattingOptions2.LabelPositioning); } set { SetOption(CSharpFormattingOptions2.LabelPositioning, (LabelPositionOptions)value); } } public int NewLines_AnonymousTypeInitializer_EachMember { get { return GetBooleanOption(CSharpFormattingOptions2.NewLineForMembersInAnonymousTypes); } set { SetBooleanOption(CSharpFormattingOptions2.NewLineForMembersInAnonymousTypes, value); } } public int NewLines_Braces_AnonymousMethod { get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInAnonymousMethods); } set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInAnonymousMethods, value); } } public int NewLines_Braces_AnonymousTypeInitializer { get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInAnonymousTypes); } set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInAnonymousTypes, value); } } public int NewLines_Braces_ControlFlow { get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInControlBlocks); } set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInControlBlocks, value); } } public int NewLines_Braces_LambdaExpressionBody { get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInLambdaExpressionBody); } set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInLambdaExpressionBody, value); } } public int NewLines_Braces_Method { get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInMethods); } set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInMethods, value); } } public int NewLines_Braces_Property { get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInProperties); } set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInProperties, value); } } public int NewLines_Braces_Accessor { get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInAccessors); } set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInAccessors, value); } } public int NewLines_Braces_ObjectInitializer { get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInObjectCollectionArrayInitializers); } set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInObjectCollectionArrayInitializers, value); } } public int NewLines_Braces_Type { get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInTypes); } set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInTypes, value); } } public int NewLines_Keywords_Catch { get { return GetBooleanOption(CSharpFormattingOptions2.NewLineForCatch); } set { SetBooleanOption(CSharpFormattingOptions2.NewLineForCatch, value); } } public int NewLines_Keywords_Else { get { return GetBooleanOption(CSharpFormattingOptions2.NewLineForElse); } set { SetBooleanOption(CSharpFormattingOptions2.NewLineForElse, value); } } public int NewLines_Keywords_Finally { get { return GetBooleanOption(CSharpFormattingOptions2.NewLineForFinally); } set { SetBooleanOption(CSharpFormattingOptions2.NewLineForFinally, value); } } public int NewLines_ObjectInitializer_EachMember { get { return GetBooleanOption(CSharpFormattingOptions2.NewLineForMembersInObjectInit); } set { SetBooleanOption(CSharpFormattingOptions2.NewLineForMembersInObjectInit, value); } } public int NewLines_QueryExpression_EachClause { get { return GetBooleanOption(CSharpFormattingOptions2.NewLineForClausesInQuery); } set { SetBooleanOption(CSharpFormattingOptions2.NewLineForClausesInQuery, value); } } public int Space_AfterBasesColon { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceAfterColonInBaseTypeDeclaration); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceAfterColonInBaseTypeDeclaration, value); } } public int Space_AfterCast { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceAfterCast); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceAfterCast, value); } } public int Space_AfterComma { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceAfterComma); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceAfterComma, value); } } public int Space_AfterDot { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceAfterDot); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceAfterDot, value); } } public int Space_AfterMethodCallName { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceAfterMethodCallName); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceAfterMethodCallName, value); } } public int Space_AfterMethodDeclarationName { get { return GetBooleanOption(CSharpFormattingOptions2.SpacingAfterMethodDeclarationName); } set { SetBooleanOption(CSharpFormattingOptions2.SpacingAfterMethodDeclarationName, value); } } public int Space_AfterSemicolonsInForStatement { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceAfterSemicolonsInForStatement); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceAfterSemicolonsInForStatement, value); } } public int Space_AroundBinaryOperator { get { return GetOption(CSharpFormattingOptions2.SpacingAroundBinaryOperator) == BinaryOperatorSpacingOptions.Single ? 1 : 0; } set { SetOption(CSharpFormattingOptions2.SpacingAroundBinaryOperator, value == 1 ? BinaryOperatorSpacingOptions.Single : BinaryOperatorSpacingOptions.Ignore); } } public int Space_BeforeBasesColon { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBeforeColonInBaseTypeDeclaration); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceBeforeColonInBaseTypeDeclaration, value); } } public int Space_BeforeComma { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBeforeComma); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceBeforeComma, value); } } public int Space_BeforeDot { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBeforeDot); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceBeforeDot, value); } } public int Space_BeforeOpenSquare { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBeforeOpenSquareBracket); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceBeforeOpenSquareBracket, value); } } public int Space_BeforeSemicolonsInForStatement { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBeforeSemicolonsInForStatement); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceBeforeSemicolonsInForStatement, value); } } public int Space_BetweenEmptyMethodCallParentheses { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBetweenEmptyMethodCallParentheses); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceBetweenEmptyMethodCallParentheses, value); } } public int Space_BetweenEmptyMethodDeclarationParentheses { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBetweenEmptyMethodDeclarationParentheses); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceBetweenEmptyMethodDeclarationParentheses, value); } } public int Space_BetweenEmptySquares { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBetweenEmptySquareBrackets); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceBetweenEmptySquareBrackets, value); } } public int Space_InControlFlowConstruct { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceAfterControlFlowStatementKeyword); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceAfterControlFlowStatementKeyword, value); } } public int Space_WithinCastParentheses { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceWithinCastParentheses); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceWithinCastParentheses, value); } } public int Space_WithinExpressionParentheses { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceWithinExpressionParentheses); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceWithinExpressionParentheses, value); } } public int Space_WithinMethodCallParentheses { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceWithinMethodCallParentheses); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceWithinMethodCallParentheses, value); } } public int Space_WithinMethodDeclarationParentheses { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceWithinMethodDeclarationParenthesis); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceWithinMethodDeclarationParenthesis, value); } } public int Space_WithinOtherParentheses { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceWithinOtherParentheses); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceWithinOtherParentheses, value); } } public int Space_WithinSquares { get { return GetBooleanOption(CSharpFormattingOptions2.SpaceWithinSquareBrackets); } set { SetBooleanOption(CSharpFormattingOptions2.SpaceWithinSquareBrackets, value); } } public int Wrapping_IgnoreSpacesAroundBinaryOperators { get { return (int)GetOption(CSharpFormattingOptions2.SpacingAroundBinaryOperator); } set { SetOption(CSharpFormattingOptions2.SpacingAroundBinaryOperator, (BinaryOperatorSpacingOptions)value); } } public int Wrapping_IgnoreSpacesAroundVariableDeclaration { get { return GetBooleanOption(CSharpFormattingOptions2.SpacesIgnoreAroundVariableDeclaration); } set { SetBooleanOption(CSharpFormattingOptions2.SpacesIgnoreAroundVariableDeclaration, value); } } public int Wrapping_KeepStatementsOnSingleLine { get { return GetBooleanOption(CSharpFormattingOptions2.WrappingKeepStatementsOnSingleLine); } set { SetBooleanOption(CSharpFormattingOptions2.WrappingKeepStatementsOnSingleLine, value); } } public int Wrapping_PreserveSingleLine { get { return GetBooleanOption(CSharpFormattingOptions2.WrappingPreserveSingleLine); } set { SetBooleanOption(CSharpFormattingOptions2.WrappingPreserveSingleLine, value); } } public int Formatting_TriggerOnPaste { get { return GetBooleanOption(FormattingOptions2.FormatOnPaste); } set { SetBooleanOption(FormattingOptions2.FormatOnPaste, value); } } public int Formatting_TriggerOnStatementCompletion { get { return GetBooleanOption(FormattingOptions2.AutoFormattingOnSemicolon); } set { SetBooleanOption(FormattingOptions2.AutoFormattingOnSemicolon, value); } } public int AutoFormattingOnTyping { get { return GetBooleanOption(FormattingOptions2.AutoFormattingOnTyping); } set { SetBooleanOption(FormattingOptions2.AutoFormattingOnTyping, value); } } } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/Features/LanguageServer/Protocol/Handler/Diagnostics/DocumentPullDiagonsticHandlerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Diagnostics { [ExportLspRequestHandlerProvider, Shared] [ProvidesMethod(MSLSPMethods.DocumentPullDiagnosticName)] internal class DocumentPullDiagonsticHandlerProvider : AbstractRequestHandlerProvider { private readonly IDiagnosticService _diagnosticService; private readonly IDiagnosticAnalyzerService _analyzerService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DocumentPullDiagonsticHandlerProvider( IDiagnosticService diagnosticService, IDiagnosticAnalyzerService analyzerService) { _diagnosticService = diagnosticService; _analyzerService = analyzerService; } public override ImmutableArray<IRequestHandler> CreateRequestHandlers() { return ImmutableArray.Create<IRequestHandler>(new DocumentPullDiagnosticHandler(_diagnosticService, _analyzerService)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Diagnostics { [ExportLspRequestHandlerProvider, Shared] [ProvidesMethod(MSLSPMethods.DocumentPullDiagnosticName)] internal class DocumentPullDiagonsticHandlerProvider : AbstractRequestHandlerProvider { private readonly IDiagnosticService _diagnosticService; private readonly IDiagnosticAnalyzerService _analyzerService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DocumentPullDiagonsticHandlerProvider( IDiagnosticService diagnosticService, IDiagnosticAnalyzerService analyzerService) { _diagnosticService = diagnosticService; _analyzerService = analyzerService; } public override ImmutableArray<IRequestHandler> CreateRequestHandlers() { return ImmutableArray.Create<IRequestHandler>(new DocumentPullDiagnosticHandler(_diagnosticService, _analyzerService)); } } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/VisualStudio/Core/Def/Implementation/Library/ILibraryService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.VsNavInfo; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library { internal interface ILibraryService : ILanguageService { NavInfoFactory NavInfoFactory { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.VsNavInfo; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library { internal interface ILibraryService : ILanguageService { NavInfoFactory NavInfoFactory { get; } } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/Features/CSharp/Portable/AddMissingReference/CSharpAddMissingReferenceCodeFixProvider.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.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.AddMissingReference; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.SymbolSearch; namespace Microsoft.CodeAnalysis.CSharp.AddMissingReference { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AddMissingReference), Shared] [ExtensionOrder(After = PredefinedCodeFixProviderNames.SimplifyNames)] internal class CSharpAddMissingReferenceCodeFixProvider : AbstractAddMissingReferenceCodeFixProvider { private const string CS0012 = nameof(CS0012); // The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'ProjectA, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(CS0012); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpAddMissingReferenceCodeFixProvider() { } /// <summary>For testing purposes only (so that tests can pass in mock values)</summary> [SuppressMessage("RoslynDiagnosticsReliability", "RS0034:Exported parts should have [ImportingConstructor]", Justification = "Used incorrectly by tests")] internal CSharpAddMissingReferenceCodeFixProvider( IPackageInstallerService installerService, ISymbolSearchService symbolSearchService) : base(installerService, symbolSearchService) { } } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.AddMissingReference; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.SymbolSearch; namespace Microsoft.CodeAnalysis.CSharp.AddMissingReference { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AddMissingReference), Shared] [ExtensionOrder(After = PredefinedCodeFixProviderNames.SimplifyNames)] internal class CSharpAddMissingReferenceCodeFixProvider : AbstractAddMissingReferenceCodeFixProvider { private const string CS0012 = nameof(CS0012); // The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'ProjectA, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(CS0012); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpAddMissingReferenceCodeFixProvider() { } /// <summary>For testing purposes only (so that tests can pass in mock values)</summary> [SuppressMessage("RoslynDiagnosticsReliability", "RS0034:Exported parts should have [ImportingConstructor]", Justification = "Used incorrectly by tests")] internal CSharpAddMissingReferenceCodeFixProvider( IPackageInstallerService installerService, ISymbolSearchService symbolSearchService) : base(installerService, symbolSearchService) { } } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/Compilers/Core/Portable/Syntax/LineMapping.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.Text; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a line mapping defined by a single line mapping directive (<c>#line</c> in C# or <c>#ExternalSource</c> in VB). /// </summary> public readonly struct LineMapping : IEquatable<LineMapping> { /// <summary> /// The span in the syntax tree containing the line mapping directive. /// </summary> public readonly LinePositionSpan Span { get; } /// <summary> /// The optional offset in the syntax tree for the line immediately following an enhanced <c>#line</c> directive in C#. /// </summary> public readonly int? CharacterOffset { get; } /// <summary> /// If the line mapping directive maps the span into an explicitly specified file the <see cref="FileLinePositionSpan.HasMappedPath"/> is true. /// If the path is not mapped <see cref="FileLinePositionSpan.Path"/> is empty and <see cref="FileLinePositionSpan.HasMappedPath"/> is false. /// If the line mapping directive marks hidden code <see cref="FileLinePositionSpan.IsValid"/> is false. /// </summary> public readonly FileLinePositionSpan MappedSpan { get; } public LineMapping(LinePositionSpan span, int? characterOffset, FileLinePositionSpan mappedSpan) { Span = span; CharacterOffset = characterOffset; MappedSpan = mappedSpan; } /// <summary> /// True if the line mapping marks hidden code. /// </summary> public bool IsHidden => !MappedSpan.IsValid; public override bool Equals(object? obj) => obj is LineMapping other && Equals(other); public bool Equals(LineMapping other) => Span.Equals(other.Span) && CharacterOffset.Equals(other.CharacterOffset) && MappedSpan.Equals(other.MappedSpan); public override int GetHashCode() => Hash.Combine(Hash.Combine(Span.GetHashCode(), CharacterOffset.GetHashCode()), MappedSpan.GetHashCode()); public static bool operator ==(LineMapping left, LineMapping right) => left.Equals(right); public static bool operator !=(LineMapping left, LineMapping right) => !(left == right); public override string? ToString() { var builder = new StringBuilder(); builder.Append(Span); if (CharacterOffset.HasValue) { builder.Append(","); builder.Append(CharacterOffset.GetValueOrDefault()); } builder.Append(" -> "); builder.Append(MappedSpan); return builder.ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a line mapping defined by a single line mapping directive (<c>#line</c> in C# or <c>#ExternalSource</c> in VB). /// </summary> public readonly struct LineMapping : IEquatable<LineMapping> { /// <summary> /// The span in the syntax tree containing the line mapping directive. /// </summary> public readonly LinePositionSpan Span { get; } /// <summary> /// The optional offset in the syntax tree for the line immediately following an enhanced <c>#line</c> directive in C#. /// </summary> public readonly int? CharacterOffset { get; } /// <summary> /// If the line mapping directive maps the span into an explicitly specified file the <see cref="FileLinePositionSpan.HasMappedPath"/> is true. /// If the path is not mapped <see cref="FileLinePositionSpan.Path"/> is empty and <see cref="FileLinePositionSpan.HasMappedPath"/> is false. /// If the line mapping directive marks hidden code <see cref="FileLinePositionSpan.IsValid"/> is false. /// </summary> public readonly FileLinePositionSpan MappedSpan { get; } public LineMapping(LinePositionSpan span, int? characterOffset, FileLinePositionSpan mappedSpan) { Span = span; CharacterOffset = characterOffset; MappedSpan = mappedSpan; } /// <summary> /// True if the line mapping marks hidden code. /// </summary> public bool IsHidden => !MappedSpan.IsValid; public override bool Equals(object? obj) => obj is LineMapping other && Equals(other); public bool Equals(LineMapping other) => Span.Equals(other.Span) && CharacterOffset.Equals(other.CharacterOffset) && MappedSpan.Equals(other.MappedSpan); public override int GetHashCode() => Hash.Combine(Hash.Combine(Span.GetHashCode(), CharacterOffset.GetHashCode()), MappedSpan.GetHashCode()); public static bool operator ==(LineMapping left, LineMapping right) => left.Equals(right); public static bool operator !=(LineMapping left, LineMapping right) => !(left == right); public override string? ToString() { var builder = new StringBuilder(); builder.Append(Span); if (CharacterOffset.HasValue) { builder.Append(","); builder.Append(CharacterOffset.GetValueOrDefault()); } builder.Append(" -> "); builder.Append(MappedSpan); return builder.ToString(); } } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_Conditional.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.Globalization Imports System.IO Imports System.Reflection Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AttributeTests_Conditional Inherits BasicTestBase #Region "Conditional Attribute Type tests" #Region "Common Helpers" Private Shared ReadOnly s_commonTestSource_ConditionalAttrDefs As String = <![CDATA[ Imports System Imports System.Diagnostics ' Applied conditional attribute <Conditional("cond1")> _ Public Class PreservedAppliedAttribute Inherits Attribute End Class <Conditional("cond2")> _ Public Class OmittedAppliedAttribute Inherits Attribute End Class ' Inherited conditional attribute <Conditional("cond3_dummy")> _ Public Class BasePreservedInheritedAttribute Inherits Attribute End Class <Conditional("cond3")> _ Public Class PreservedInheritedAttribute Inherits BasePreservedInheritedAttribute End Class <Conditional("cond4")> _ Public Class BaseOmittedInheritedAttribute Inherits Attribute End Class <Conditional("cond5")> _ Public Class OmittedInheritedAttribute Inherits BaseOmittedInheritedAttribute End Class ' Multiple conditional attributes <Conditional("cond6"), Conditional("cond7"), Conditional("cond8")> _ Public Class PreservedMultipleAttribute Inherits Attribute End Class <Conditional("cond9")> _ Public Class BaseOmittedMultipleAttribute Inherits Attribute End Class <Conditional("cond10"), Conditional("cond11")> _ Public Class OmittedMultipleAttribute Inherits BaseOmittedMultipleAttribute End Class ' Partially preserved applied conditional attribute ' This attribute has its conditional constant defined midway through the source file. Hence it is conditionally emitted in metadata only for some symbols. <Conditional("condForPartiallyPreservedAppliedAttribute")> _ Public Class PartiallyPreservedAppliedAttribute Inherits Attribute End Class ]]>.Value Private Shared ReadOnly s_commonTestSource_ConditionalAttributesApplied As String = <![CDATA[ <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public MustInherit Class Z <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public Function m(<PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> param1 As Integer) _ As <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> Integer #Const condForPartiallyPreservedAppliedAttribute = True Return 0 End Function <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public f As Integer <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public Property p1() As <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> Integer <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Get Return m_p1 End Get #Const condForPartiallyPreservedAppliedAttribute = False <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Set(value As Integer) m_p1 = value End Set End Property Private m_p1 As Integer <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public MustOverride ReadOnly Property p2() As <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> Integer <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public MustOverride Property p3() As <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> Integer <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public Event e As Action End Class #Const condForPartiallyPreservedAppliedAttribute = "TrueAgain" <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public Enum E <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ A = 1 End Enum <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public Structure S End Structure Public Class Test Public Shared Sub Main() End Sub End Class ]]>.Value Private ReadOnly _commonValidatorForCondAttrType As Func(Of Boolean, Action(Of ModuleSymbol)) = Function(isFromSource As Boolean) _ Sub(m As ModuleSymbol) ' Each Tuple indicates: <Attributes, hasPartiallyPreservedAppliedAttribute> ' PartiallyPreservedAppliedAttribute has its conditional constant defined midway through the source file. ' Hence this attribute is emitted in metadata only for some symbols. Dim attributesArrayBuilder = ArrayBuilder(Of Tuple(Of ImmutableArray(Of VisualBasicAttributeData), Boolean)).GetInstance() Dim classZ = m.GlobalNamespace.GetTypeMember("Z") attributesArrayBuilder.Add(Tuple.Create(classZ.GetAttributes(), False)) Dim methodM = classZ.GetMember(Of MethodSymbol)("m") attributesArrayBuilder.Add(Tuple.Create(methodM.GetAttributes(), False)) attributesArrayBuilder.Add(Tuple.Create(methodM.GetReturnTypeAttributes(), False)) Dim param1 = methodM.Parameters(0) attributesArrayBuilder.Add(Tuple.Create(param1.GetAttributes(), False)) Dim fieldF = classZ.GetMember(Of FieldSymbol)("f") attributesArrayBuilder.Add(Tuple.Create(fieldF.GetAttributes(), True)) Dim propP1 = classZ.GetMember(Of PropertySymbol)("p1") attributesArrayBuilder.Add(Tuple.Create(propP1.GetAttributes(), True)) Dim propGetMethod = propP1.GetMethod attributesArrayBuilder.Add(Tuple.Create(propGetMethod.GetAttributes(), True)) attributesArrayBuilder.Add(Tuple.Create(propGetMethod.GetReturnTypeAttributes(), True)) Dim propSetMethod = propP1.SetMethod attributesArrayBuilder.Add(Tuple.Create(propSetMethod.GetAttributes(), False)) Assert.Equal(0, propSetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, propSetMethod.Parameters(0).GetAttributes().Length) Dim propP2 = classZ.GetMember(Of PropertySymbol)("p2") attributesArrayBuilder.Add(Tuple.Create(propP2.GetAttributes(), False)) propGetMethod = propP2.GetMethod Assert.Equal(0, propGetMethod.GetAttributes().Length) attributesArrayBuilder.Add(Tuple.Create(propGetMethod.GetReturnTypeAttributes(), False)) Dim propP3 = classZ.GetMember(Of PropertySymbol)("p3") attributesArrayBuilder.Add(Tuple.Create(propP3.GetAttributes(), False)) propGetMethod = propP3.GetMethod Assert.Equal(0, propGetMethod.GetAttributes().Length) attributesArrayBuilder.Add(Tuple.Create(propGetMethod.GetReturnTypeAttributes(), False)) propSetMethod = propP3.SetMethod Assert.Equal(0, propSetMethod.GetAttributes().Length) Assert.Equal(0, propSetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, propSetMethod.Parameters(0).GetAttributes().Length) Dim eventE = classZ.GetMember(Of EventSymbol)("e") attributesArrayBuilder.Add(Tuple.Create(eventE.GetAttributes(), False)) If isFromSource Then Assert.Equal(0, eventE.AssociatedField.GetAttributes().Length) Assert.Equal(0, eventE.AddMethod.GetAttributes().Length) Assert.Equal(0, eventE.RemoveMethod.GetAttributes().Length) Else AssertEx.Equal({"CompilerGeneratedAttribute"}, GetAttributeNames(eventE.AddMethod.GetAttributes())) AssertEx.Equal({"CompilerGeneratedAttribute"}, GetAttributeNames(eventE.RemoveMethod.GetAttributes())) End If Assert.Equal(0, eventE.AddMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, eventE.RemoveMethod.GetReturnTypeAttributes().Length) Dim enumE = m.GlobalNamespace.GetTypeMember("E") attributesArrayBuilder.Add(Tuple.Create(enumE.GetAttributes(), True)) Dim fieldA = enumE.GetMember(Of FieldSymbol)("A") attributesArrayBuilder.Add(Tuple.Create(fieldA.GetAttributes(), True)) Dim structS = m.GlobalNamespace.GetTypeMember("S") attributesArrayBuilder.Add(Tuple.Create(structS.GetAttributes(), True)) For Each tup In attributesArrayBuilder ' PreservedAppliedAttribute and OmittedAppliedAttribute have applied conditional attributes, such that ' (a) PreservedAppliedAttribute is conditionally applied to symbols ' (b) OmittedAppliedAttribute is conditionally NOT applied to symbols ' PreservedInheritedAttribute and OmittedInheritedAttribute have inherited conditional attributes, such that ' (a) PreservedInheritedAttribute is conditionally applied to symbols ' (b) OmittedInheritedAttribute is conditionally NOT applied to symbols ' PreservedMultipleAttribute and OmittedMultipleAttribute have multiple applied/inherited conditional attributes, such that ' (a) PreservedMultipleAttribute is conditionally applied to symbols ' (b) OmittedMultipleAttribute is conditionally NOT applied to symbols ' PartiallyPreservedAppliedAttribute has its conditional constant defined midway through the source file. ' Hence this attribute is emitted in metadata only for some symbols. Dim attributesArray As ImmutableArray(Of VisualBasicAttributeData) = tup.Item1 Dim actualAttributeNames = GetAttributeNames(attributesArray) If isFromSource Then ' All attributes should be present for source symbols AssertEx.SetEqual({"PreservedAppliedAttribute", "OmittedAppliedAttribute", "PreservedInheritedAttribute", "OmittedInheritedAttribute", "PreservedMultipleAttribute", "OmittedMultipleAttribute", "PartiallyPreservedAppliedAttribute"}, actualAttributeNames) Else Dim hasPartiallyPreservedAppliedAttribute = tup.Item2 Dim expectedAttributeNames As String() If Not hasPartiallyPreservedAppliedAttribute Then ' Only PreservedAppliedAttribute, PreservedInheritedAttribute, PreservedMultipleAttribute should be emitted in metadata expectedAttributeNames = {"PreservedAppliedAttribute", "PreservedInheritedAttribute", "PreservedMultipleAttribute"} Else ' PartiallyPreservedAppliedAttribute must also be emitted in metadata expectedAttributeNames = {"PreservedAppliedAttribute", "PreservedInheritedAttribute", "PreservedMultipleAttribute", "PartiallyPreservedAppliedAttribute"} End If AssertEx.SetEqual(expectedAttributeNames, actualAttributeNames) End If Next attributesArrayBuilder.Free() End Sub Private Sub TestConditionAttributeType_SameSource(condDefs As String, preprocessorSymbols As ImmutableArray(Of KeyValuePair(Of String, Object))) ' Same source file Debug.Assert(Not preprocessorSymbols.IsDefault) Dim parseOpts = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbols) Dim testSource As String = condDefs & s_commonTestSource_ConditionalAttrDefs & s_commonTestSource_ConditionalAttributesApplied Dim compilation = CreateCompilationWithMscorlib40({Parse(testSource, parseOpts)}, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation, sourceSymbolValidator:=_commonValidatorForCondAttrType(True), symbolValidator:=_commonValidatorForCondAttrType(False), expectedOutput:="") End Sub Private Sub TestConditionAttributeType_SameSource(condDefs As String) TestConditionAttributeType_SameSource(condDefs, ImmutableArray.Create(Of KeyValuePair(Of String, Object))()) End Sub Private Sub TestConditionAttributeType_DifferentSource(condDefsSrcFile1 As String, condDefsSrcFile2 As String) TestConditionAttributeType_DifferentSource(condDefsSrcFile1, ImmutableArray.Create(Of KeyValuePair(Of String, Object))(), condDefsSrcFile2, ImmutableArray.Create(Of KeyValuePair(Of String, Object))()) End Sub Private Sub TestConditionAttributeType_DifferentSource(condDefsSrcFile1 As String, preprocessorSymbolsSrcFile1 As ImmutableArray(Of KeyValuePair(Of String, Object)), condDefsSrcFile2 As String, preprocessorSymbolsSrcFile2 As ImmutableArray(Of KeyValuePair(Of String, Object))) Dim source1 As String = condDefsSrcFile1 & s_commonTestSource_ConditionalAttrDefs Dim source2 As String = condDefsSrcFile2 & <![CDATA[ Imports System Imports System.Diagnostics ]]>.Value & s_commonTestSource_ConditionalAttributesApplied Debug.Assert(Not preprocessorSymbolsSrcFile1.IsDefault) Dim parseOpts1 = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbolsSrcFile1) Debug.Assert(Not preprocessorSymbolsSrcFile2.IsDefault) Dim parseOpts2 = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbolsSrcFile2) ' Different source files, same compilation Dim comp = CreateCompilationWithMscorlib40({Parse(source1, parseOpts1), Parse(source2, parseOpts2)}, options:=TestOptions.ReleaseExe) CompileAndVerify(comp, sourceSymbolValidator:=_commonValidatorForCondAttrType(True), symbolValidator:=_commonValidatorForCondAttrType(False), expectedOutput:="") ' Different source files, different compilation Dim comp1 = CreateCompilationWithMscorlib40({Parse(source1, parseOpts1)}, options:=TestOptions.ReleaseDll) Dim comp2 = VisualBasicCompilation.Create("comp2", {Parse(source2, parseOpts2)}, {MscorlibRef, New VisualBasicCompilationReference(comp1)}, options:=TestOptions.ReleaseExe) CompileAndVerify(comp2, sourceSymbolValidator:=_commonValidatorForCondAttrType(True), symbolValidator:=_commonValidatorForCondAttrType(False), expectedOutput:="") End Sub #End Region #Region "Tests" <Fact> Public Sub TestConditionAttributeType_01_SourceDefines() Dim conditionalDefs As String = <![CDATA[ #Const cond1 = 1 #Const cond3 = "" #Const cond6 = True ]]>.Value TestConditionAttributeType_SameSource(conditionalDefs) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond2 = 1 #Const cond5 = "" #Const cond7 = True ]]>.Value TestConditionAttributeType_DifferentSource(conditionalDefsDummy, conditionalDefs) End Sub <Fact> Public Sub TestConditionAttributeType_01_CommandLineDefines() Dim preprocessorSymbols = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond1", 1), New KeyValuePair(Of String, Object)("cond3", ""), New KeyValuePair(Of String, Object)("cond6", True)) TestConditionAttributeType_SameSource(condDefs:="", preprocessorSymbols:=preprocessorSymbols) Dim preprocessorSymbolsDummy = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond2", 1), New KeyValuePair(Of String, Object)("cond5", ""), New KeyValuePair(Of String, Object)("cond7", True)) TestConditionAttributeType_DifferentSource(condDefsSrcFile1:="", preprocessorSymbolsSrcFile1:=preprocessorSymbolsDummy, condDefsSrcFile2:="", preprocessorSymbolsSrcFile2:=preprocessorSymbols) End Sub <Fact> Public Sub TestConditionAttributeType_02_SourceDefines() Dim conditionalDefs As String = <![CDATA[ #Const cond1 = 1 #Const cond2 = 1.0 ' Decimal type value is not considered for CC constants. #Const cond3 = "" #Const cond4 = True ' Conditional attributes are not inherited from base type. #Const cond5 = 1 #Const cond5 = Nothing ' The last definition holds for CC constants. #Const cond6 = True #Const cond7 = 0 ' One of the conditional symbol is zero, but other conditional symbols for the attribute type are defined. #Const cond8 = 2 ' Multiple conditional symbols defined. ]]>.Value TestConditionAttributeType_SameSource(conditionalDefs) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond2 = 1 #Const cond3_dummy = 0 #Const cond5 = "" #Const cond7 = True #Const cond8 = True #Const cond9 = True #Const cond10 = True #Const cond11 = True ]]>.Value TestConditionAttributeType_DifferentSource(conditionalDefsDummy, conditionalDefs) End Sub <Fact> Public Sub TestConditionAttributeType_02_CommandLineDefines() ' Mix and match source and command line defines. Dim preprocessorSymbols = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond1", 1), New KeyValuePair(Of String, Object)("cond2", 1.0), New KeyValuePair(Of String, Object)("cond3", ""), New KeyValuePair(Of String, Object)("cond4", True), New KeyValuePair(Of String, Object)("cond5", 1)) Dim conditionalDefs As String = <![CDATA[ #Const cond5 = Nothing ' Source definition for CC constants overrides command line /define definitions. #Const cond6 = True ' Mix match source and command line defines. #Const cond7 = 0 ' One of the conditional symbol is zero, but other conditional symbols for the attribute type are defined. #Const cond8 = 2 ' Multiple conditional symbols defined. ]]>.Value TestConditionAttributeType_SameSource(conditionalDefs, preprocessorSymbols:=preprocessorSymbols) ' Mix and match source and command line defines. Dim preprocessorSymbolsDummy = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond2", 1), New KeyValuePair(Of String, Object)("cond3_dummy", 1)) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond5 = "" #Const cond7 = True #Const cond8 = True #Const cond9 = True #Const cond10 = True #Const cond11 = True ]]>.Value TestConditionAttributeType_DifferentSource(conditionalDefsDummy, preprocessorSymbolsDummy, conditionalDefs, preprocessorSymbols) End Sub <Fact> Public Sub TestNestedTypeMember() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Diagnostics <Conditional(Outer.Nested.ConstStr)> _ <Outer> _ Class Outer Inherits Attribute Public Class Nested Public Const ConstStr As String = "str" End Class End Class ]]> </file> </compilation> CompileAndVerify(source) End Sub #End Region #End Region #Region "Conditional Method tests" #Region "Common Helpers" Private Shared ReadOnly s_commonTestSource_ConditionalMethodDefs As String = <![CDATA[ Imports System Imports System.Diagnostics Public Class BaseZ <Conditional("cond3_base")> _ Public Overridable Sub PreservedCalls_InheritedConditional_Method() System.Console.WriteLine("BaseZ.PreservedCalls_InheritedConditional_Method") End Sub <Conditional("cond4_base")> _ Public Overridable Sub OmittedCalls_InheritedConditional_Method() System.Console.WriteLine("BaseZ.OmittedCalls_InheritedConditional_Method") End Sub End Class Public Interface I ' Conditional attributes are ignored for interface methods, but respected for implementing methods. <Conditional("dummy")> Sub PartiallyPreservedCalls_Interface_Method() End Interface Public Class Z Inherits BaseZ Implements I <Conditional("cond1")> _ Public Sub PreservedCalls_AppliedConditional_Method() System.Console.WriteLine("Z.PreservedCalls_AppliedConditional_Method") End Sub <Conditional("cond2")> _ Public Sub OmittedCalls_AppliedConditional_Method() System.Console.WriteLine("Z.OmittedCalls_AppliedConditional_Method") End Sub ' Conditional symbols are not inherited by overriding methods in VB <Conditional("cond3")> _ Public Overrides Sub PreservedCalls_InheritedConditional_Method() System.Console.WriteLine("Z.PreservedCalls_InheritedConditional_Method") End Sub #Const cond4_base = "Conditional symbols are not inherited by overriding methods in VB" <Conditional("cond4")> _ Public Overrides Sub OmittedCalls_InheritedConditional_Method() System.Console.WriteLine("Z.OmittedCalls_InheritedConditional_Method") End Sub <Conditional("cond5"), Conditional("cond6")> _ Public Sub PreservedCalls_MultipleConditional_Method() System.Console.WriteLine("Z.PreservedCalls_MultipleConditional_Method") End Sub <Conditional("cond7"), Conditional("cond8")> _ Public Sub OmittedCalls_MultipleConditional_Method() System.Console.WriteLine("Z.OmittedCalls_MultipleConditional_Method") End Sub ' Conditional attributes are ignored for interface methods, but respected for implementing methods. <Conditional("cond9")> Public Sub PartiallyPreservedCalls_Interface_Method() Implements I.PartiallyPreservedCalls_Interface_Method System.Console.WriteLine("Z.PartiallyPreservedCalls_Interface_Method") End Sub ' Conditional attributes are ignored for functions <Conditional("cond10")> Public Function PreservedCalls_Function() As Integer System.Console.WriteLine("Z.PreservedCalls_Function") Return 0 End Function <Conditional(""), Conditional(Nothing)> _ Public Sub OmittedCalls_AlwaysFalseConditional_Method() System.Console.WriteLine("Z.OmittedCalls_AlwaysFalseConditional_Method") End Sub <Conditional("condForPartiallyPreservedAppliedAttribute")> Public Sub PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(i As Integer) System.Console.WriteLine("Z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method" & i) End Sub End Class ]]>.Value Private Shared ReadOnly s_commonTestSource_ConditionalMethodCalls As String = <![CDATA[ Module Module1 Public Sub Main() Dim z = New Z() z.PreservedCalls_AppliedConditional_Method() z.OmittedCalls_AppliedConditional_Method() z.PreservedCalls_InheritedConditional_Method() z.OmittedCalls_InheritedConditional_Method() z.PreservedCalls_MultipleConditional_Method() z.OmittedCalls_MultipleConditional_Method() z.OmittedCalls_AlwaysFalseConditional_Method() z.PartiallyPreservedCalls_Interface_Method() ' Omitted DirectCast(z, I).PartiallyPreservedCalls_Interface_Method() ' Preserved Console.WriteLine(z.PreservedCalls_Function()) ' Second and fourth calls are preserved, first, third and fifth calls are omitted. z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(1) # Const condForPartiallyPreservedAppliedAttribute = True z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(2) # Const condForPartiallyPreservedAppliedAttribute = 0 z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(3) # Const condForPartiallyPreservedAppliedAttribute = "TrueAgain" z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(4) # Const condForPartiallyPreservedAppliedAttribute = Nothing z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(5) End Sub End Module ]]>.Value Private Shared ReadOnly s_commonExpectedOutput_ConditionalMethodsTest As String = "Z.PreservedCalls_AppliedConditional_Method" & Environment.NewLine & "Z.PreservedCalls_InheritedConditional_Method" & Environment.NewLine & "Z.PreservedCalls_MultipleConditional_Method" & Environment.NewLine & "Z.PartiallyPreservedCalls_Interface_Method" & Environment.NewLine & "Z.PreservedCalls_Function" & Environment.NewLine & "0" & Environment.NewLine & "Z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method2" & Environment.NewLine & "Z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method4" & Environment.NewLine Private Sub TestConditionalMethod_SameSource(condDefs As String) TestConditionalMethod_SameSource(condDefs, ImmutableArray.Create(Of KeyValuePair(Of String, Object))()) End Sub Private Sub TestConditionalMethod_SameSource(condDefs As String, preprocessorSymbols As ImmutableArray(Of KeyValuePair(Of String, Object))) ' Same source file Debug.Assert(Not preprocessorSymbols.IsDefault) Dim parseOpts = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbols) Dim testSource As String = condDefs & s_commonTestSource_ConditionalMethodDefs & s_commonTestSource_ConditionalMethodCalls Dim comp = VisualBasicCompilation.Create(GetUniqueName(), {Parse(testSource, parseOpts)}, {MscorlibRef, SystemCoreRef, MsvbRef}) CompileAndVerify(comp, expectedOutput:=s_commonExpectedOutput_ConditionalMethodsTest) End Sub Private Sub TestConditionalMethod_DifferentSource(condDefsSrcFile1 As String, condDefsSrcFile2 As String) TestConditionalMethod_DifferentSource(condDefsSrcFile1, ImmutableArray.Create(Of KeyValuePair(Of String, Object))(), condDefsSrcFile2, ImmutableArray.Create(Of KeyValuePair(Of String, Object))()) End Sub Private Sub TestConditionalMethod_DifferentSource(condDefsSrcFile1 As String, preprocessorSymbolsSrcFile1 As ImmutableArray(Of KeyValuePair(Of String, Object)), condDefsSrcFile2 As String, preprocessorSymbolsSrcFile2 As ImmutableArray(Of KeyValuePair(Of String, Object))) Dim source1 As String = condDefsSrcFile1 & s_commonTestSource_ConditionalMethodDefs Dim source2 As String = condDefsSrcFile2 & <![CDATA[ Imports System Imports System.Diagnostics ]]>.Value & s_commonTestSource_ConditionalMethodCalls Debug.Assert(Not preprocessorSymbolsSrcFile1.IsDefault) Dim parseOpts1 = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbolsSrcFile1) Debug.Assert(Not preprocessorSymbolsSrcFile2.IsDefault) Dim parseOpts2 = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbolsSrcFile2) ' Different source files, same compilation Dim comp = VisualBasicCompilation.Create(GetUniqueName(), {Parse(source1, parseOpts1), Parse(source2, parseOpts2)}, {MscorlibRef, MsvbRef}, TestOptions.ReleaseExe) CompileAndVerify(comp, expectedOutput:=s_commonExpectedOutput_ConditionalMethodsTest) ' Different source files, different compilation Dim comp1 = VisualBasicCompilation.Create(GetUniqueName(), {Parse(source1, parseOpts1)}, {MscorlibRef, MsvbRef}, TestOptions.ReleaseDll) Dim comp2 = VisualBasicCompilation.Create(GetUniqueName(), {Parse(source2, parseOpts2)}, {MscorlibRef, MsvbRef, comp1.ToMetadataReference()}, TestOptions.ReleaseExe) CompileAndVerify(comp2, expectedOutput:=s_commonExpectedOutput_ConditionalMethodsTest) End Sub #End Region #Region "Tests" <Fact> Public Sub TestConditionalMethod_01_SourceDefines() Dim conditionalDefs As String = <![CDATA[ #Const cond1 = 1 #Const cond3 = "" #Const cond5 = True ]]>.Value TestConditionalMethod_SameSource(conditionalDefs) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond2 = 1 #Const cond5 = "" #Const cond7 = True ]]>.Value TestConditionalMethod_DifferentSource(conditionalDefsDummy, conditionalDefs) End Sub <Fact> Public Sub TestConditionalMethod_01_CommandLineDefines() Dim preprocessorSymbols = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond1", 1), New KeyValuePair(Of String, Object)("cond3", ""), New KeyValuePair(Of String, Object)("cond5", True)) TestConditionalMethod_SameSource(condDefs:="", preprocessorSymbols:=preprocessorSymbols) Dim preprocessorSymbolsDummy = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond2", 1), New KeyValuePair(Of String, Object)("cond5", ""), New KeyValuePair(Of String, Object)("cond7", True)) TestConditionalMethod_DifferentSource(condDefsSrcFile1:="", preprocessorSymbolsSrcFile1:=preprocessorSymbolsDummy, condDefsSrcFile2:="", preprocessorSymbolsSrcFile2:=preprocessorSymbols) End Sub <Fact> Public Sub TestConditionalMethod_02_SourceDefines() Dim conditionalDefs As String = <![CDATA[ #Const cond1 = 1 #Const cond2 = 1.0 ' Decimal type value is not considered for CC constants. #Const cond3 = "" #Const cond4_base = True ' Conditional attributes are not inherited from base type. #Const cond5 = 1 #Const cond5 = 0 ' One of the conditional symbol is zero, but other conditional symbols for the attribute type are defined. #Const cond6 = True #Const cond7 = 0 #Const cond3 = True ' The last definition holds for CC constants. ]]>.Value TestConditionalMethod_SameSource(conditionalDefs) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond2 = 1 #Const cond3_dummy = 0 #Const cond5 = "" #Const cond7 = True #Const cond8 = True #Const cond9 = True #Const cond10 = True #Const cond11 = True ]]>.Value TestConditionalMethod_DifferentSource(conditionalDefsDummy, conditionalDefs) End Sub <Fact> Public Sub TestConditionalMethod_02_CommandLineDefines() ' Mix and match source and command line defines. Dim preprocessorSymbols = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond1", 1), New KeyValuePair(Of String, Object)("cond2", 1.0), New KeyValuePair(Of String, Object)("cond3", ""), New KeyValuePair(Of String, Object)("cond4_base", True), New KeyValuePair(Of String, Object)("cond5", 1)) Dim conditionalDefs As String = <![CDATA[ #Const cond5 = 0 ' One of the conditional symbol is zero, but other conditional symbols for the attribute type are defined. #Const cond6 = True #Const cond7 = 0 #Const cond3 = True ' The last definition holds for CC constants. ]]>.Value TestConditionalMethod_SameSource(conditionalDefs, preprocessorSymbols) ' Mix and match source and command line defines. Dim preprocessorSymbolsDummy = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond2", 1), New KeyValuePair(Of String, Object)("cond3_dummy", 0), New KeyValuePair(Of String, Object)("cond5", True)) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond7 = True #Const cond8 = True #Const cond9 = True #Const cond10 = True #Const cond11 = True ]]>.Value TestConditionalMethod_DifferentSource(conditionalDefsDummy, preprocessorSymbolsDummy, conditionalDefs, preprocessorSymbols) End Sub <WorkItem(546089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546089")> <Fact> Public Sub CaseInsensitivityTest() Dim source = <compilation> <file name="a.vb"> Imports System Module Test &lt;System.Diagnostics.Conditional("VAR4")&gt; Sub Sub1() Console.WriteLine("Sub1 Called") End Sub Sub Main() #Const var4 = True Sub1() End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[Sub1 Called]]>) End Sub <WorkItem(546089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546089")> <Fact> Public Sub CaseInsensitivityTest_02() Dim source = <compilation> <file name="a.vb"> Imports System Module Test &lt;System.Diagnostics.Conditional("VAR4")&gt; Sub Sub1() Console.WriteLine("Sub1 Called") End Sub #Const VAR4 = False Sub Main() #Const var4 = True Sub1() End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[Sub1 Called]]>) End Sub <WorkItem(546094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546094")> <Fact> Public Sub ConditionalAttributeOnPropertySetter() Dim source = <compilation> <file name="a.vb"> Imports System Class TestClass WriteOnly Property goo() As String &lt;Diagnostics.Conditional("N")&gt; Set(ByVal Value As String) Console.WriteLine("Property Called") End Set End Property End Class Module M1 Sub Main() Dim t As New TestClass() t.goo = "abds" End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[Property Called]]>) End Sub #End Region <WorkItem(1003274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1003274")> <Fact> Public Sub ConditionalAttributeInNetModule() Const source = " Imports System.Diagnostics Class C Sub M() N1() N2() End Sub <Conditional(""Defined"")> Sub N1() End Sub <Conditional(""Undefined"")> Sub N2() End Sub End Class " Dim parseOptions As New VisualBasicParseOptions(preprocessorSymbols:={New KeyValuePair(Of String, Object)("Defined", True)}) Dim comp = CreateCompilationWithMscorlib40({VisualBasicSyntaxTree.ParseText(source, parseOptions)}, options:=TestOptions.ReleaseModule) CompileAndVerify(comp, verify:=Verification.Fails).VerifyIL("C.M", " { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""Sub C.N1()"" IL_0006: ret } ") End Sub #End Region End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Globalization Imports System.IO Imports System.Reflection Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AttributeTests_Conditional Inherits BasicTestBase #Region "Conditional Attribute Type tests" #Region "Common Helpers" Private Shared ReadOnly s_commonTestSource_ConditionalAttrDefs As String = <![CDATA[ Imports System Imports System.Diagnostics ' Applied conditional attribute <Conditional("cond1")> _ Public Class PreservedAppliedAttribute Inherits Attribute End Class <Conditional("cond2")> _ Public Class OmittedAppliedAttribute Inherits Attribute End Class ' Inherited conditional attribute <Conditional("cond3_dummy")> _ Public Class BasePreservedInheritedAttribute Inherits Attribute End Class <Conditional("cond3")> _ Public Class PreservedInheritedAttribute Inherits BasePreservedInheritedAttribute End Class <Conditional("cond4")> _ Public Class BaseOmittedInheritedAttribute Inherits Attribute End Class <Conditional("cond5")> _ Public Class OmittedInheritedAttribute Inherits BaseOmittedInheritedAttribute End Class ' Multiple conditional attributes <Conditional("cond6"), Conditional("cond7"), Conditional("cond8")> _ Public Class PreservedMultipleAttribute Inherits Attribute End Class <Conditional("cond9")> _ Public Class BaseOmittedMultipleAttribute Inherits Attribute End Class <Conditional("cond10"), Conditional("cond11")> _ Public Class OmittedMultipleAttribute Inherits BaseOmittedMultipleAttribute End Class ' Partially preserved applied conditional attribute ' This attribute has its conditional constant defined midway through the source file. Hence it is conditionally emitted in metadata only for some symbols. <Conditional("condForPartiallyPreservedAppliedAttribute")> _ Public Class PartiallyPreservedAppliedAttribute Inherits Attribute End Class ]]>.Value Private Shared ReadOnly s_commonTestSource_ConditionalAttributesApplied As String = <![CDATA[ <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public MustInherit Class Z <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public Function m(<PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> param1 As Integer) _ As <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> Integer #Const condForPartiallyPreservedAppliedAttribute = True Return 0 End Function <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public f As Integer <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public Property p1() As <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> Integer <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Get Return m_p1 End Get #Const condForPartiallyPreservedAppliedAttribute = False <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Set(value As Integer) m_p1 = value End Set End Property Private m_p1 As Integer <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public MustOverride ReadOnly Property p2() As <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> Integer <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public MustOverride Property p3() As <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> Integer <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public Event e As Action End Class #Const condForPartiallyPreservedAppliedAttribute = "TrueAgain" <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public Enum E <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ A = 1 End Enum <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public Structure S End Structure Public Class Test Public Shared Sub Main() End Sub End Class ]]>.Value Private ReadOnly _commonValidatorForCondAttrType As Func(Of Boolean, Action(Of ModuleSymbol)) = Function(isFromSource As Boolean) _ Sub(m As ModuleSymbol) ' Each Tuple indicates: <Attributes, hasPartiallyPreservedAppliedAttribute> ' PartiallyPreservedAppliedAttribute has its conditional constant defined midway through the source file. ' Hence this attribute is emitted in metadata only for some symbols. Dim attributesArrayBuilder = ArrayBuilder(Of Tuple(Of ImmutableArray(Of VisualBasicAttributeData), Boolean)).GetInstance() Dim classZ = m.GlobalNamespace.GetTypeMember("Z") attributesArrayBuilder.Add(Tuple.Create(classZ.GetAttributes(), False)) Dim methodM = classZ.GetMember(Of MethodSymbol)("m") attributesArrayBuilder.Add(Tuple.Create(methodM.GetAttributes(), False)) attributesArrayBuilder.Add(Tuple.Create(methodM.GetReturnTypeAttributes(), False)) Dim param1 = methodM.Parameters(0) attributesArrayBuilder.Add(Tuple.Create(param1.GetAttributes(), False)) Dim fieldF = classZ.GetMember(Of FieldSymbol)("f") attributesArrayBuilder.Add(Tuple.Create(fieldF.GetAttributes(), True)) Dim propP1 = classZ.GetMember(Of PropertySymbol)("p1") attributesArrayBuilder.Add(Tuple.Create(propP1.GetAttributes(), True)) Dim propGetMethod = propP1.GetMethod attributesArrayBuilder.Add(Tuple.Create(propGetMethod.GetAttributes(), True)) attributesArrayBuilder.Add(Tuple.Create(propGetMethod.GetReturnTypeAttributes(), True)) Dim propSetMethod = propP1.SetMethod attributesArrayBuilder.Add(Tuple.Create(propSetMethod.GetAttributes(), False)) Assert.Equal(0, propSetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, propSetMethod.Parameters(0).GetAttributes().Length) Dim propP2 = classZ.GetMember(Of PropertySymbol)("p2") attributesArrayBuilder.Add(Tuple.Create(propP2.GetAttributes(), False)) propGetMethod = propP2.GetMethod Assert.Equal(0, propGetMethod.GetAttributes().Length) attributesArrayBuilder.Add(Tuple.Create(propGetMethod.GetReturnTypeAttributes(), False)) Dim propP3 = classZ.GetMember(Of PropertySymbol)("p3") attributesArrayBuilder.Add(Tuple.Create(propP3.GetAttributes(), False)) propGetMethod = propP3.GetMethod Assert.Equal(0, propGetMethod.GetAttributes().Length) attributesArrayBuilder.Add(Tuple.Create(propGetMethod.GetReturnTypeAttributes(), False)) propSetMethod = propP3.SetMethod Assert.Equal(0, propSetMethod.GetAttributes().Length) Assert.Equal(0, propSetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, propSetMethod.Parameters(0).GetAttributes().Length) Dim eventE = classZ.GetMember(Of EventSymbol)("e") attributesArrayBuilder.Add(Tuple.Create(eventE.GetAttributes(), False)) If isFromSource Then Assert.Equal(0, eventE.AssociatedField.GetAttributes().Length) Assert.Equal(0, eventE.AddMethod.GetAttributes().Length) Assert.Equal(0, eventE.RemoveMethod.GetAttributes().Length) Else AssertEx.Equal({"CompilerGeneratedAttribute"}, GetAttributeNames(eventE.AddMethod.GetAttributes())) AssertEx.Equal({"CompilerGeneratedAttribute"}, GetAttributeNames(eventE.RemoveMethod.GetAttributes())) End If Assert.Equal(0, eventE.AddMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, eventE.RemoveMethod.GetReturnTypeAttributes().Length) Dim enumE = m.GlobalNamespace.GetTypeMember("E") attributesArrayBuilder.Add(Tuple.Create(enumE.GetAttributes(), True)) Dim fieldA = enumE.GetMember(Of FieldSymbol)("A") attributesArrayBuilder.Add(Tuple.Create(fieldA.GetAttributes(), True)) Dim structS = m.GlobalNamespace.GetTypeMember("S") attributesArrayBuilder.Add(Tuple.Create(structS.GetAttributes(), True)) For Each tup In attributesArrayBuilder ' PreservedAppliedAttribute and OmittedAppliedAttribute have applied conditional attributes, such that ' (a) PreservedAppliedAttribute is conditionally applied to symbols ' (b) OmittedAppliedAttribute is conditionally NOT applied to symbols ' PreservedInheritedAttribute and OmittedInheritedAttribute have inherited conditional attributes, such that ' (a) PreservedInheritedAttribute is conditionally applied to symbols ' (b) OmittedInheritedAttribute is conditionally NOT applied to symbols ' PreservedMultipleAttribute and OmittedMultipleAttribute have multiple applied/inherited conditional attributes, such that ' (a) PreservedMultipleAttribute is conditionally applied to symbols ' (b) OmittedMultipleAttribute is conditionally NOT applied to symbols ' PartiallyPreservedAppliedAttribute has its conditional constant defined midway through the source file. ' Hence this attribute is emitted in metadata only for some symbols. Dim attributesArray As ImmutableArray(Of VisualBasicAttributeData) = tup.Item1 Dim actualAttributeNames = GetAttributeNames(attributesArray) If isFromSource Then ' All attributes should be present for source symbols AssertEx.SetEqual({"PreservedAppliedAttribute", "OmittedAppliedAttribute", "PreservedInheritedAttribute", "OmittedInheritedAttribute", "PreservedMultipleAttribute", "OmittedMultipleAttribute", "PartiallyPreservedAppliedAttribute"}, actualAttributeNames) Else Dim hasPartiallyPreservedAppliedAttribute = tup.Item2 Dim expectedAttributeNames As String() If Not hasPartiallyPreservedAppliedAttribute Then ' Only PreservedAppliedAttribute, PreservedInheritedAttribute, PreservedMultipleAttribute should be emitted in metadata expectedAttributeNames = {"PreservedAppliedAttribute", "PreservedInheritedAttribute", "PreservedMultipleAttribute"} Else ' PartiallyPreservedAppliedAttribute must also be emitted in metadata expectedAttributeNames = {"PreservedAppliedAttribute", "PreservedInheritedAttribute", "PreservedMultipleAttribute", "PartiallyPreservedAppliedAttribute"} End If AssertEx.SetEqual(expectedAttributeNames, actualAttributeNames) End If Next attributesArrayBuilder.Free() End Sub Private Sub TestConditionAttributeType_SameSource(condDefs As String, preprocessorSymbols As ImmutableArray(Of KeyValuePair(Of String, Object))) ' Same source file Debug.Assert(Not preprocessorSymbols.IsDefault) Dim parseOpts = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbols) Dim testSource As String = condDefs & s_commonTestSource_ConditionalAttrDefs & s_commonTestSource_ConditionalAttributesApplied Dim compilation = CreateCompilationWithMscorlib40({Parse(testSource, parseOpts)}, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation, sourceSymbolValidator:=_commonValidatorForCondAttrType(True), symbolValidator:=_commonValidatorForCondAttrType(False), expectedOutput:="") End Sub Private Sub TestConditionAttributeType_SameSource(condDefs As String) TestConditionAttributeType_SameSource(condDefs, ImmutableArray.Create(Of KeyValuePair(Of String, Object))()) End Sub Private Sub TestConditionAttributeType_DifferentSource(condDefsSrcFile1 As String, condDefsSrcFile2 As String) TestConditionAttributeType_DifferentSource(condDefsSrcFile1, ImmutableArray.Create(Of KeyValuePair(Of String, Object))(), condDefsSrcFile2, ImmutableArray.Create(Of KeyValuePair(Of String, Object))()) End Sub Private Sub TestConditionAttributeType_DifferentSource(condDefsSrcFile1 As String, preprocessorSymbolsSrcFile1 As ImmutableArray(Of KeyValuePair(Of String, Object)), condDefsSrcFile2 As String, preprocessorSymbolsSrcFile2 As ImmutableArray(Of KeyValuePair(Of String, Object))) Dim source1 As String = condDefsSrcFile1 & s_commonTestSource_ConditionalAttrDefs Dim source2 As String = condDefsSrcFile2 & <![CDATA[ Imports System Imports System.Diagnostics ]]>.Value & s_commonTestSource_ConditionalAttributesApplied Debug.Assert(Not preprocessorSymbolsSrcFile1.IsDefault) Dim parseOpts1 = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbolsSrcFile1) Debug.Assert(Not preprocessorSymbolsSrcFile2.IsDefault) Dim parseOpts2 = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbolsSrcFile2) ' Different source files, same compilation Dim comp = CreateCompilationWithMscorlib40({Parse(source1, parseOpts1), Parse(source2, parseOpts2)}, options:=TestOptions.ReleaseExe) CompileAndVerify(comp, sourceSymbolValidator:=_commonValidatorForCondAttrType(True), symbolValidator:=_commonValidatorForCondAttrType(False), expectedOutput:="") ' Different source files, different compilation Dim comp1 = CreateCompilationWithMscorlib40({Parse(source1, parseOpts1)}, options:=TestOptions.ReleaseDll) Dim comp2 = VisualBasicCompilation.Create("comp2", {Parse(source2, parseOpts2)}, {MscorlibRef, New VisualBasicCompilationReference(comp1)}, options:=TestOptions.ReleaseExe) CompileAndVerify(comp2, sourceSymbolValidator:=_commonValidatorForCondAttrType(True), symbolValidator:=_commonValidatorForCondAttrType(False), expectedOutput:="") End Sub #End Region #Region "Tests" <Fact> Public Sub TestConditionAttributeType_01_SourceDefines() Dim conditionalDefs As String = <![CDATA[ #Const cond1 = 1 #Const cond3 = "" #Const cond6 = True ]]>.Value TestConditionAttributeType_SameSource(conditionalDefs) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond2 = 1 #Const cond5 = "" #Const cond7 = True ]]>.Value TestConditionAttributeType_DifferentSource(conditionalDefsDummy, conditionalDefs) End Sub <Fact> Public Sub TestConditionAttributeType_01_CommandLineDefines() Dim preprocessorSymbols = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond1", 1), New KeyValuePair(Of String, Object)("cond3", ""), New KeyValuePair(Of String, Object)("cond6", True)) TestConditionAttributeType_SameSource(condDefs:="", preprocessorSymbols:=preprocessorSymbols) Dim preprocessorSymbolsDummy = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond2", 1), New KeyValuePair(Of String, Object)("cond5", ""), New KeyValuePair(Of String, Object)("cond7", True)) TestConditionAttributeType_DifferentSource(condDefsSrcFile1:="", preprocessorSymbolsSrcFile1:=preprocessorSymbolsDummy, condDefsSrcFile2:="", preprocessorSymbolsSrcFile2:=preprocessorSymbols) End Sub <Fact> Public Sub TestConditionAttributeType_02_SourceDefines() Dim conditionalDefs As String = <![CDATA[ #Const cond1 = 1 #Const cond2 = 1.0 ' Decimal type value is not considered for CC constants. #Const cond3 = "" #Const cond4 = True ' Conditional attributes are not inherited from base type. #Const cond5 = 1 #Const cond5 = Nothing ' The last definition holds for CC constants. #Const cond6 = True #Const cond7 = 0 ' One of the conditional symbol is zero, but other conditional symbols for the attribute type are defined. #Const cond8 = 2 ' Multiple conditional symbols defined. ]]>.Value TestConditionAttributeType_SameSource(conditionalDefs) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond2 = 1 #Const cond3_dummy = 0 #Const cond5 = "" #Const cond7 = True #Const cond8 = True #Const cond9 = True #Const cond10 = True #Const cond11 = True ]]>.Value TestConditionAttributeType_DifferentSource(conditionalDefsDummy, conditionalDefs) End Sub <Fact> Public Sub TestConditionAttributeType_02_CommandLineDefines() ' Mix and match source and command line defines. Dim preprocessorSymbols = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond1", 1), New KeyValuePair(Of String, Object)("cond2", 1.0), New KeyValuePair(Of String, Object)("cond3", ""), New KeyValuePair(Of String, Object)("cond4", True), New KeyValuePair(Of String, Object)("cond5", 1)) Dim conditionalDefs As String = <![CDATA[ #Const cond5 = Nothing ' Source definition for CC constants overrides command line /define definitions. #Const cond6 = True ' Mix match source and command line defines. #Const cond7 = 0 ' One of the conditional symbol is zero, but other conditional symbols for the attribute type are defined. #Const cond8 = 2 ' Multiple conditional symbols defined. ]]>.Value TestConditionAttributeType_SameSource(conditionalDefs, preprocessorSymbols:=preprocessorSymbols) ' Mix and match source and command line defines. Dim preprocessorSymbolsDummy = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond2", 1), New KeyValuePair(Of String, Object)("cond3_dummy", 1)) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond5 = "" #Const cond7 = True #Const cond8 = True #Const cond9 = True #Const cond10 = True #Const cond11 = True ]]>.Value TestConditionAttributeType_DifferentSource(conditionalDefsDummy, preprocessorSymbolsDummy, conditionalDefs, preprocessorSymbols) End Sub <Fact> Public Sub TestNestedTypeMember() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Diagnostics <Conditional(Outer.Nested.ConstStr)> _ <Outer> _ Class Outer Inherits Attribute Public Class Nested Public Const ConstStr As String = "str" End Class End Class ]]> </file> </compilation> CompileAndVerify(source) End Sub #End Region #End Region #Region "Conditional Method tests" #Region "Common Helpers" Private Shared ReadOnly s_commonTestSource_ConditionalMethodDefs As String = <![CDATA[ Imports System Imports System.Diagnostics Public Class BaseZ <Conditional("cond3_base")> _ Public Overridable Sub PreservedCalls_InheritedConditional_Method() System.Console.WriteLine("BaseZ.PreservedCalls_InheritedConditional_Method") End Sub <Conditional("cond4_base")> _ Public Overridable Sub OmittedCalls_InheritedConditional_Method() System.Console.WriteLine("BaseZ.OmittedCalls_InheritedConditional_Method") End Sub End Class Public Interface I ' Conditional attributes are ignored for interface methods, but respected for implementing methods. <Conditional("dummy")> Sub PartiallyPreservedCalls_Interface_Method() End Interface Public Class Z Inherits BaseZ Implements I <Conditional("cond1")> _ Public Sub PreservedCalls_AppliedConditional_Method() System.Console.WriteLine("Z.PreservedCalls_AppliedConditional_Method") End Sub <Conditional("cond2")> _ Public Sub OmittedCalls_AppliedConditional_Method() System.Console.WriteLine("Z.OmittedCalls_AppliedConditional_Method") End Sub ' Conditional symbols are not inherited by overriding methods in VB <Conditional("cond3")> _ Public Overrides Sub PreservedCalls_InheritedConditional_Method() System.Console.WriteLine("Z.PreservedCalls_InheritedConditional_Method") End Sub #Const cond4_base = "Conditional symbols are not inherited by overriding methods in VB" <Conditional("cond4")> _ Public Overrides Sub OmittedCalls_InheritedConditional_Method() System.Console.WriteLine("Z.OmittedCalls_InheritedConditional_Method") End Sub <Conditional("cond5"), Conditional("cond6")> _ Public Sub PreservedCalls_MultipleConditional_Method() System.Console.WriteLine("Z.PreservedCalls_MultipleConditional_Method") End Sub <Conditional("cond7"), Conditional("cond8")> _ Public Sub OmittedCalls_MultipleConditional_Method() System.Console.WriteLine("Z.OmittedCalls_MultipleConditional_Method") End Sub ' Conditional attributes are ignored for interface methods, but respected for implementing methods. <Conditional("cond9")> Public Sub PartiallyPreservedCalls_Interface_Method() Implements I.PartiallyPreservedCalls_Interface_Method System.Console.WriteLine("Z.PartiallyPreservedCalls_Interface_Method") End Sub ' Conditional attributes are ignored for functions <Conditional("cond10")> Public Function PreservedCalls_Function() As Integer System.Console.WriteLine("Z.PreservedCalls_Function") Return 0 End Function <Conditional(""), Conditional(Nothing)> _ Public Sub OmittedCalls_AlwaysFalseConditional_Method() System.Console.WriteLine("Z.OmittedCalls_AlwaysFalseConditional_Method") End Sub <Conditional("condForPartiallyPreservedAppliedAttribute")> Public Sub PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(i As Integer) System.Console.WriteLine("Z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method" & i) End Sub End Class ]]>.Value Private Shared ReadOnly s_commonTestSource_ConditionalMethodCalls As String = <![CDATA[ Module Module1 Public Sub Main() Dim z = New Z() z.PreservedCalls_AppliedConditional_Method() z.OmittedCalls_AppliedConditional_Method() z.PreservedCalls_InheritedConditional_Method() z.OmittedCalls_InheritedConditional_Method() z.PreservedCalls_MultipleConditional_Method() z.OmittedCalls_MultipleConditional_Method() z.OmittedCalls_AlwaysFalseConditional_Method() z.PartiallyPreservedCalls_Interface_Method() ' Omitted DirectCast(z, I).PartiallyPreservedCalls_Interface_Method() ' Preserved Console.WriteLine(z.PreservedCalls_Function()) ' Second and fourth calls are preserved, first, third and fifth calls are omitted. z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(1) # Const condForPartiallyPreservedAppliedAttribute = True z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(2) # Const condForPartiallyPreservedAppliedAttribute = 0 z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(3) # Const condForPartiallyPreservedAppliedAttribute = "TrueAgain" z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(4) # Const condForPartiallyPreservedAppliedAttribute = Nothing z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(5) End Sub End Module ]]>.Value Private Shared ReadOnly s_commonExpectedOutput_ConditionalMethodsTest As String = "Z.PreservedCalls_AppliedConditional_Method" & Environment.NewLine & "Z.PreservedCalls_InheritedConditional_Method" & Environment.NewLine & "Z.PreservedCalls_MultipleConditional_Method" & Environment.NewLine & "Z.PartiallyPreservedCalls_Interface_Method" & Environment.NewLine & "Z.PreservedCalls_Function" & Environment.NewLine & "0" & Environment.NewLine & "Z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method2" & Environment.NewLine & "Z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method4" & Environment.NewLine Private Sub TestConditionalMethod_SameSource(condDefs As String) TestConditionalMethod_SameSource(condDefs, ImmutableArray.Create(Of KeyValuePair(Of String, Object))()) End Sub Private Sub TestConditionalMethod_SameSource(condDefs As String, preprocessorSymbols As ImmutableArray(Of KeyValuePair(Of String, Object))) ' Same source file Debug.Assert(Not preprocessorSymbols.IsDefault) Dim parseOpts = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbols) Dim testSource As String = condDefs & s_commonTestSource_ConditionalMethodDefs & s_commonTestSource_ConditionalMethodCalls Dim comp = VisualBasicCompilation.Create(GetUniqueName(), {Parse(testSource, parseOpts)}, {MscorlibRef, SystemCoreRef, MsvbRef}) CompileAndVerify(comp, expectedOutput:=s_commonExpectedOutput_ConditionalMethodsTest) End Sub Private Sub TestConditionalMethod_DifferentSource(condDefsSrcFile1 As String, condDefsSrcFile2 As String) TestConditionalMethod_DifferentSource(condDefsSrcFile1, ImmutableArray.Create(Of KeyValuePair(Of String, Object))(), condDefsSrcFile2, ImmutableArray.Create(Of KeyValuePair(Of String, Object))()) End Sub Private Sub TestConditionalMethod_DifferentSource(condDefsSrcFile1 As String, preprocessorSymbolsSrcFile1 As ImmutableArray(Of KeyValuePair(Of String, Object)), condDefsSrcFile2 As String, preprocessorSymbolsSrcFile2 As ImmutableArray(Of KeyValuePair(Of String, Object))) Dim source1 As String = condDefsSrcFile1 & s_commonTestSource_ConditionalMethodDefs Dim source2 As String = condDefsSrcFile2 & <![CDATA[ Imports System Imports System.Diagnostics ]]>.Value & s_commonTestSource_ConditionalMethodCalls Debug.Assert(Not preprocessorSymbolsSrcFile1.IsDefault) Dim parseOpts1 = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbolsSrcFile1) Debug.Assert(Not preprocessorSymbolsSrcFile2.IsDefault) Dim parseOpts2 = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbolsSrcFile2) ' Different source files, same compilation Dim comp = VisualBasicCompilation.Create(GetUniqueName(), {Parse(source1, parseOpts1), Parse(source2, parseOpts2)}, {MscorlibRef, MsvbRef}, TestOptions.ReleaseExe) CompileAndVerify(comp, expectedOutput:=s_commonExpectedOutput_ConditionalMethodsTest) ' Different source files, different compilation Dim comp1 = VisualBasicCompilation.Create(GetUniqueName(), {Parse(source1, parseOpts1)}, {MscorlibRef, MsvbRef}, TestOptions.ReleaseDll) Dim comp2 = VisualBasicCompilation.Create(GetUniqueName(), {Parse(source2, parseOpts2)}, {MscorlibRef, MsvbRef, comp1.ToMetadataReference()}, TestOptions.ReleaseExe) CompileAndVerify(comp2, expectedOutput:=s_commonExpectedOutput_ConditionalMethodsTest) End Sub #End Region #Region "Tests" <Fact> Public Sub TestConditionalMethod_01_SourceDefines() Dim conditionalDefs As String = <![CDATA[ #Const cond1 = 1 #Const cond3 = "" #Const cond5 = True ]]>.Value TestConditionalMethod_SameSource(conditionalDefs) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond2 = 1 #Const cond5 = "" #Const cond7 = True ]]>.Value TestConditionalMethod_DifferentSource(conditionalDefsDummy, conditionalDefs) End Sub <Fact> Public Sub TestConditionalMethod_01_CommandLineDefines() Dim preprocessorSymbols = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond1", 1), New KeyValuePair(Of String, Object)("cond3", ""), New KeyValuePair(Of String, Object)("cond5", True)) TestConditionalMethod_SameSource(condDefs:="", preprocessorSymbols:=preprocessorSymbols) Dim preprocessorSymbolsDummy = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond2", 1), New KeyValuePair(Of String, Object)("cond5", ""), New KeyValuePair(Of String, Object)("cond7", True)) TestConditionalMethod_DifferentSource(condDefsSrcFile1:="", preprocessorSymbolsSrcFile1:=preprocessorSymbolsDummy, condDefsSrcFile2:="", preprocessorSymbolsSrcFile2:=preprocessorSymbols) End Sub <Fact> Public Sub TestConditionalMethod_02_SourceDefines() Dim conditionalDefs As String = <![CDATA[ #Const cond1 = 1 #Const cond2 = 1.0 ' Decimal type value is not considered for CC constants. #Const cond3 = "" #Const cond4_base = True ' Conditional attributes are not inherited from base type. #Const cond5 = 1 #Const cond5 = 0 ' One of the conditional symbol is zero, but other conditional symbols for the attribute type are defined. #Const cond6 = True #Const cond7 = 0 #Const cond3 = True ' The last definition holds for CC constants. ]]>.Value TestConditionalMethod_SameSource(conditionalDefs) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond2 = 1 #Const cond3_dummy = 0 #Const cond5 = "" #Const cond7 = True #Const cond8 = True #Const cond9 = True #Const cond10 = True #Const cond11 = True ]]>.Value TestConditionalMethod_DifferentSource(conditionalDefsDummy, conditionalDefs) End Sub <Fact> Public Sub TestConditionalMethod_02_CommandLineDefines() ' Mix and match source and command line defines. Dim preprocessorSymbols = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond1", 1), New KeyValuePair(Of String, Object)("cond2", 1.0), New KeyValuePair(Of String, Object)("cond3", ""), New KeyValuePair(Of String, Object)("cond4_base", True), New KeyValuePair(Of String, Object)("cond5", 1)) Dim conditionalDefs As String = <![CDATA[ #Const cond5 = 0 ' One of the conditional symbol is zero, but other conditional symbols for the attribute type are defined. #Const cond6 = True #Const cond7 = 0 #Const cond3 = True ' The last definition holds for CC constants. ]]>.Value TestConditionalMethod_SameSource(conditionalDefs, preprocessorSymbols) ' Mix and match source and command line defines. Dim preprocessorSymbolsDummy = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond2", 1), New KeyValuePair(Of String, Object)("cond3_dummy", 0), New KeyValuePair(Of String, Object)("cond5", True)) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond7 = True #Const cond8 = True #Const cond9 = True #Const cond10 = True #Const cond11 = True ]]>.Value TestConditionalMethod_DifferentSource(conditionalDefsDummy, preprocessorSymbolsDummy, conditionalDefs, preprocessorSymbols) End Sub <WorkItem(546089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546089")> <Fact> Public Sub CaseInsensitivityTest() Dim source = <compilation> <file name="a.vb"> Imports System Module Test &lt;System.Diagnostics.Conditional("VAR4")&gt; Sub Sub1() Console.WriteLine("Sub1 Called") End Sub Sub Main() #Const var4 = True Sub1() End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[Sub1 Called]]>) End Sub <WorkItem(546089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546089")> <Fact> Public Sub CaseInsensitivityTest_02() Dim source = <compilation> <file name="a.vb"> Imports System Module Test &lt;System.Diagnostics.Conditional("VAR4")&gt; Sub Sub1() Console.WriteLine("Sub1 Called") End Sub #Const VAR4 = False Sub Main() #Const var4 = True Sub1() End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[Sub1 Called]]>) End Sub <WorkItem(546094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546094")> <Fact> Public Sub ConditionalAttributeOnPropertySetter() Dim source = <compilation> <file name="a.vb"> Imports System Class TestClass WriteOnly Property goo() As String &lt;Diagnostics.Conditional("N")&gt; Set(ByVal Value As String) Console.WriteLine("Property Called") End Set End Property End Class Module M1 Sub Main() Dim t As New TestClass() t.goo = "abds" End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[Property Called]]>) End Sub #End Region <WorkItem(1003274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1003274")> <Fact> Public Sub ConditionalAttributeInNetModule() Const source = " Imports System.Diagnostics Class C Sub M() N1() N2() End Sub <Conditional(""Defined"")> Sub N1() End Sub <Conditional(""Undefined"")> Sub N2() End Sub End Class " Dim parseOptions As New VisualBasicParseOptions(preprocessorSymbols:={New KeyValuePair(Of String, Object)("Defined", True)}) Dim comp = CreateCompilationWithMscorlib40({VisualBasicSyntaxTree.ParseText(source, parseOptions)}, options:=TestOptions.ReleaseModule) CompileAndVerify(comp, verify:=Verification.Fails).VerifyIL("C.M", " { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""Sub C.N1()"" IL_0006: ret } ") End Sub #End Region End Class End Namespace
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SelectedMembers/VisualBasicSelectedMembers.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.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices Friend Class VisualBasicSelectedMembers Inherits AbstractSelectedMembers(Of StatementSyntax, FieldDeclarationSyntax, PropertyStatementSyntax, TypeBlockSyntax, ModifiedIdentifierSyntax) Public Shared ReadOnly Instance As New VisualBasicSelectedMembers() Private Sub New() End Sub Protected Overrides Function GetAllDeclarators(field As FieldDeclarationSyntax) As IEnumerable(Of ModifiedIdentifierSyntax) Return field.Declarators.SelectMany(Function(d) d.Names) End Function Protected Overrides Function GetMembers(containingType As TypeBlockSyntax) As SyntaxList(Of StatementSyntax) Return containingType.Members End Function Protected Overrides Function GetPropertyIdentifier(declarator As PropertyStatementSyntax) As SyntaxToken Return declarator.Identifier End Function Protected Overrides Function GetVariableIdentifier(declarator As ModifiedIdentifierSyntax) As SyntaxToken Return declarator.Identifier 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.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices Friend Class VisualBasicSelectedMembers Inherits AbstractSelectedMembers(Of StatementSyntax, FieldDeclarationSyntax, PropertyStatementSyntax, TypeBlockSyntax, ModifiedIdentifierSyntax) Public Shared ReadOnly Instance As New VisualBasicSelectedMembers() Private Sub New() End Sub Protected Overrides Function GetAllDeclarators(field As FieldDeclarationSyntax) As IEnumerable(Of ModifiedIdentifierSyntax) Return field.Declarators.SelectMany(Function(d) d.Names) End Function Protected Overrides Function GetMembers(containingType As TypeBlockSyntax) As SyntaxList(Of StatementSyntax) Return containingType.Members End Function Protected Overrides Function GetPropertyIdentifier(declarator As PropertyStatementSyntax) As SyntaxToken Return declarator.Identifier End Function Protected Overrides Function GetVariableIdentifier(declarator As ModifiedIdentifierSyntax) As SyntaxToken Return declarator.Identifier End Function End Class End Namespace
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/Features/LanguageServer/Protocol/Handler/SemanticTokens/TokenModifiers.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.LanguageServer.Handler.SemanticTokens { /// <summary> /// The LSP modifiers from <see cref="VisualStudio.LanguageServer.Protocol.SemanticTokenModifiers"/> /// Roslyn currently supports. Enum is used to signify the modifier(s) that apply to a given token. /// </summary> [Flags] internal enum TokenModifiers { None = 0, Static = 1, ReassignedVariable = 2, } }
// Licensed to the .NET Foundation under one or more 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.LanguageServer.Handler.SemanticTokens { /// <summary> /// The LSP modifiers from <see cref="VisualStudio.LanguageServer.Protocol.SemanticTokenModifiers"/> /// Roslyn currently supports. Enum is used to signify the modifier(s) that apply to a given token. /// </summary> [Flags] internal enum TokenModifiers { None = 0, Static = 1, ReassignedVariable = 2, } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/Compilers/VisualBasic/Test/Emit/Semantics/StaticLocalsSemanticTests.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 Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class StaticLocalsSemanticTests Inherits BasicTestBase <Fact, WorkItem(15925, "DevDiv_Projects/Roslyn")> Public Sub Semantic_StaticLocalDeclarationInSub() Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class Module1 Public Shared Sub Main() StaticLocalInSub() StaticLocalInSub() End Sub Shared Sub StaticLocalInSub() Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[StaticLocalInSub System.Int32 1 StaticLocalInSub System.Int32 2]]>) End Sub <Fact, WorkItem(15925, "DevDiv_Projects/Roslyn")> Public Sub Semantic_StaticLocalDeclarationInSubModule() Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() StaticLocalInSub() StaticLocalInSub() End Sub Sub StaticLocalInSub() Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[StaticLocalInSub System.Int32 1 StaticLocalInSub System.Int32 2]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclarationInFunction() 'Using different Type as well Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Dim x1 = StaticLocalInFunction() x1 = StaticLocalInFunction() End Sub Function StaticLocalInFunction() As Long Static SLItem1 As Long = 1 'Type Character Console.WriteLine("StaticLocalInFunction") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 Return SLItem1 End Function End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[StaticLocalInFunction System.Int64 1 StaticLocalInFunction System.Int64 2]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclarationReferenceType() Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() StaticLocalRefType() StaticLocalRefType() StaticLocalRefType() End Sub Sub StaticLocalRefType() Static SLItem1 As String = "" SLItem1 &amp;= "*" Console.WriteLine("StaticLocalRefType") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[StaticLocalRefType System.String * StaticLocalRefType System.String ** StaticLocalRefType System.String ***]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclarationUserDefinedClass() 'With a user defined reference type (class) this should only initialize on initial invocation and then 'increment each time Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() StaticLocalUserDefinedType() StaticLocalUserDefinedType() StaticLocalUserDefinedType() End Sub Sub StaticLocalUserDefinedType() Static SLi As Integer = 1 Static SLItem1 As TestUDClass = New TestUDClass With {.ABC = SLi} SLItem1.ABC = SLi SLi += 1 Console.WriteLine("StaticLocalUserDefinedType") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value Console.WriteLine(SLItem1.ABC.ToString) 'Value End Sub End Module Class TestUDClass Public Property ABC As Integer = 1 End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[StaticLocalUserDefinedType TestUDClass TestUDClass 1 StaticLocalUserDefinedType TestUDClass TestUDClass 2 StaticLocalUserDefinedType TestUDClass TestUDClass 3 ]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclaration_InGenericType() 'Can declare in generic type, just not in generic method Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Dim x As New UDTest(Of Integer) x.Goo() x.Goo() x.Goo() End Sub End Module Public Class UDTest(Of t) Public Sub Goo() Static SLItem As Integer = 1 Console.WriteLine(SLItem.ToString) SLItem += 1 End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 3]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclaration_Keyword_NameClashInType() 'declare Escaped identifier called static Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() AvoidingNameConflicts() AvoidingNameConflicts() AvoidingNameConflicts() End Sub Sub AvoidingNameConflicts() Static [Static] As Integer = 1 Console.WriteLine([Static]) [Static] += 1 End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 3]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclaration_Keyword_NameClashEscaped() 'declare identifier and type called static both of which need to be escaped along with static Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() AvoidingNameConflicts() AvoidingNameConflicts() AvoidingNameConflicts() End Sub Sub AvoidingNameConflicts() Static [Static] As [Static] = New [Static] With {.ABC = 1} Console.WriteLine([Static].ABC) [Static].ABC += 1 End Sub End Module Class [Static] Public Property ABC As Integer End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 3]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclaration_Keyword_NameClash_Property_NoEscapingRequired() 'declare Property called static doesnt need escaping because of preceding . Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() AvoidingNameConflicts() AvoidingNameConflicts() AvoidingNameConflicts() End Sub Sub AvoidingNameConflicts() Static S1 As [Static] = New [Static] With {.Static = 1} Console.WriteLine(S1.Static) S1.Static += 1 End Sub End Module Class [Static] Public Property [Static] As Integer End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 3]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclaration_LateBound() ' test late bind ' call ToString() on object defeat the purpose Dim currCulture = Threading.Thread.CurrentThread.CurrentCulture Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture Try 'Declare static local which is late bound Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() WithTypeObject(1) WithTypeObject(2) WithTypeObject(3) End Sub Sub WithTypeObject(x As Integer) Static sl1 As Object = 1 Console.WriteLine("Prior:" &amp; sl1) Select Case x Case 1 sl1 = 1 Case 2 sl1 = "Test" Case Else sl1 = 5.5 End Select Console.WriteLine("After:" &amp; sl1) End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[Prior:1 After:1 Prior:1 After:Test Prior:Test After:5.5]]>) Catch ex As Exception Assert.Null(ex) Finally Threading.Thread.CurrentThread.CurrentCulture = currCulture End Try End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclaration_WithTypeCharacters() 'Declare static local using type identifier Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() WithTypeCharacters() WithTypeCharacters() WithTypeCharacters() End Sub Sub WithTypeCharacters() Static sl1% = 1 'integer Static sl2&amp; = 1 'Long Static sl3@ = 1 'Decimal Static sl4! = 1 'Single Static sl5# = 1 'Double Static sl6$ = "" 'String Console.WriteLine(sl1) Console.WriteLine(sl2) Console.WriteLine(sl3) Console.WriteLine(sl4.ToString(System.Globalization.CultureInfo.InvariantCulture)) Console.WriteLine(sl5.ToString(System.Globalization.CultureInfo.InvariantCulture)) Console.WriteLine(sl6) sl1 +=1 sl2 +=1 sl3 +=1 sl4 +=0.5 sl5 +=0.5 sl6 +="*" End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 1 1 1 1 2 2 2 1.5 1.5 * 3 3 3 2 2 **]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclaration_WithArrayTypes() 'Declare static local with array types Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() WithArrayType() WithArrayType() End Sub Sub WithArrayType() Static Dim sl1 As Integer() = {1, 2, 3} 'integer 'Show Values Console.WriteLine(sl1.Length) For Each i In sl1 Console.Write(i.ToString &amp; " ") Next Console.WriteLine("") sl1 = {11, 12} End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[3 1 2 3 2 11 12]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclaration_WithCollectionInitializer() 'Declare static local using collection types / extension methods and the Add would be invoked each time, Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System 'Used my own attribute for Extension attribute based upon necessary signature rather than adding a specific reference to 'System.Core which contains this normally Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method, AllowMultiple:=False, Inherited:=False)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace Public Module Module1 Public Sub Main() Dim x As New System.Collections.Generic.Stack(Of Integer) From {11, 21, 31} End Sub &lt;System.Runtime.CompilerServices.Extension&gt; Public Sub Add(x As System.Collections.Generic.Stack(Of Integer), y As Integer) Static Dim sl1 As Integer = 0 sl1 += 1 Console.WriteLine(sl1.ToString &amp; " Value:" &amp; y.ToString) x.Push(y) End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 Value:11 2 Value:21 3 Value:31]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclaration_WithDim() 'Declare static local in conjunction with a Dim keyword Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() WithTypeCharacters() WithTypeCharacters() WithTypeCharacters() End Sub Sub WithTypeCharacters() Static Dim sl1 As Integer = 1 'integer Console.WriteLine(sl1) sl1 += 1 End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 3]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclaration_WithAttribute() 'This is important because the static local can have an attribute on it whereas a normal local cannot ParseAndVerify(<![CDATA[ Imports System Public Module Module1 Public Sub Main() Goo() Goo() Goo() End Sub Sub Goo() <Test> Static a1 As Integer = 1 a1 += 1 Console.WriteLine(a1.ToString) End Sub End Module <AttributeUsage(AttributeTargets.All)> Class TestAttribute Inherits Attribute End Class ]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalInTryCatchBlock() 'The Use of Static Locals within Try/Catch/Finally Blocks 'Simple Usage Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() CatchBlock() CatchBlock() FinallyBlock() FinallyBlock() NotCalledCatchBlock() NotCalledCatchBlock() End Sub Sub CatchBlock() Try Throw New Exception Catch ex As Exception Static a As Integer = 1 Console.WriteLine(a.ToString) a += 1 End Try End Sub Sub FinallyBlock() Try Throw New Exception Catch ex As Exception Finally Static a As Integer = 1 Console.WriteLine(a.ToString) a += 1 End Try End Sub Sub NotCalledCatchBlock() Try Catch ex As Exception Static a As Integer = 1 Console.WriteLine(a.ToString) a += 1 End Try End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 1 2]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalExceptionInInitialization() Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public ExceptionThrow As Boolean = False Public Sub Main() ExceptionThrow = False test(True) 'First Time Exception thrown so it will result in static local initialized to default for second call If ExceptionThrow Then Console.WriteLine("Exception Thrown") Else Console.WriteLine("No Exception Thrown") ExceptionThrow = False test(True) 'This should result in value of default value +1 and no exception thrown on second invocation If ExceptionThrow Then Console.WriteLine("Exception Thrown") Else Console.WriteLine("No Exception Thrown") ExceptionThrow = False test(True) 'This should result in value of default value +1 and no exception thrown on second invocation If ExceptionThrow Then Console.WriteLine("Exception Thrown") Else Console.WriteLine("No Exception Thrown") End Sub Sub test(BlnThrowException As Boolean) Try Static sl As Integer = throwException(BlnThrowException) 'Something to cause exception sl += 1 Console.WriteLine(sl.ToString) Catch ex As Exception ExceptionThrow = True Finally End Try End Sub Function throwException(x As Boolean) As Integer If x = True Then Throw New Exception Else Return 1 End If End Function End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[ Exception Thrown 1 No Exception Thrown 2 No Exception Thrown]]>) 'SemanticInfoTypeTestForeach(compilation1, 1, "String()", "System.Collections.IEnumerable") 'AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="s", ReadInsideSymbol:="arr, s", ReadOutsideSymbol:="arr", ' WrittenInsideSymbol:="s", WrittenOutsideSymbol:="arr", ' AlwaysAssignedSymbol:="", DataFlowsInSymbol:="arr", DataFlowsOutSymbol:="") 'AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, ' EndPointIsReachable:=True) 'ClassfiConversionTestForeach(compilation1) 'VerifyForeachSemanticInfo(compilation1) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalInTryCatchBlock_21() 'The Use of Static Locals within Try/Catch/Finally Blocks Dim compilationDef = <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() test(False) test(True) test(False) End Sub Sub test(ThrowException As Boolean) Static sl As Integer = 1 Try If ThrowException Then Throw New Exception End If Catch ex As Exception sl += 1 End Try Console.WriteLine(sl.ToString) End Sub End Module End Module </file> </compilation> 'Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndVBRuntime(compilationDef) 'compilation.VerifyDiagnostics() End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalInTryCatchBlock_3() 'The Use of Static Locals within Try/Catch/Finally Blocks Dim compilationDef = <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() test(True) test(False) test(True) End Sub Sub test(ThrowException As Boolean) Static sl As Integer = 1 Try If ThrowException Then Throw New Exception End If Catch ex As Exception sl += 1 End Try Console.WriteLine(sl.ToString) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics() End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalInTryCatchFinallyBlock() 'The Use of Static Locals within Try/Catch/Finally Blocks Dim compilationDef = <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() CatchBlock() CatchBlock() FinallyBlock() FinallyBlock() NotCalledCatchBlock() NotCalledCatchBlock() End Sub Sub CatchBlock() Try Throw New Exception Catch ex As Exception Static a As Integer = 1 Console.WriteLine(a.ToString) a += 1 End Try End Sub Sub FinallyBlock() Try Throw New Exception Catch ex As Exception Finally Static a As Integer = 1 Console.WriteLine(a.ToString) a += 1 End Try End Sub Sub NotCalledCatchBlock() Try Catch ex As Exception Static a As Integer = 1 Console.WriteLine(a.ToString) a += 1 End Try End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 1 2]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalInTryCatchBlock_2() 'The Use of Static Locals within Try/Catch/Finally Blocks Dim compilationDef = <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() test(False) test(True) test(False) End Sub Sub test(ThrowException As Boolean) Static sl As Integer = 1 Try If ThrowException Then Throw New Exception End If Catch ex As Exception sl += 1 End Try Console.WriteLine(sl.ToString) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 2]]>) End Sub Public Sub Semantic_SameNameInDifferentMethods() 'The Use of Static Locals within shared methods with same name as static local in each method Dim compilationDef = <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Test1() Test2() Test1() Test2() End Sub Sub Test1() Static sl As Integer = 1 Console.WriteLine(sl.ToString) sl += 1 End Sub Sub Test2() Static sl As Integer = 1 Console.WriteLine(sl.ToString) sl += 1 End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 1 2 2]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_SameNameInDifferentOverloads() 'The Use of Static Locals within shared methods with same name as static local in each method Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Test() Test(1) Test() Test(1) End Sub Sub Test() Static sl As Integer = 1 Console.WriteLine(sl.ToString) sl += 1 End Sub Sub Test(x As Integer) Static sl As Integer = 1 Console.WriteLine(sl.ToString) sl += 1 End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 1 2 2]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_SharedMethods() 'The Use of Static Locals within shared methods with same name as static local in each method Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C1 Public Shared Sub Main() testMethod() testMethod2() testMethod() testMethod2() testMethod() testMethod2() End Sub Shared Sub testMethod() Static sl As Integer = 1 sl += 1 Console.WriteLine(sl.ToString) End Sub Shared Sub testMethod2() Static sl As Integer = 1 sl += 1 Console.WriteLine(sl.ToString) End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[2 2 3 3 4 4]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_OverriddenMethod() 'The Use of Static Locals in both a base and derived class with overridden method Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Dim Obj As New Base Obj.Goo() Obj.Goo() Obj.Goo() Dim ObjD As New Derived ObjD.goo() ObjD.goo() ObjD.goo() End Sub End Module Class Base Overridable Sub Goo() Static sl As Integer = 1 Console.WriteLine(sl.ToString) sl += 1 End Sub End Class Class Derived Sub goo() Static sl As Integer = 10 Console.WriteLine(sl.ToString) sl += 1 End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 3 10 11 12]]>) End Sub Public Sub Semantic_InheritanceConstructor() 'The Use of Static Locals in both a base and derived class constructor - instance method Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Dim Obj As New Base Dim ObjD As New Derived End Sub End Module Class Base Sub New() Static sl As Integer = 1 Console.WriteLine(sl.ToString) sl += 1 End Sub End Class Class Derived Inherits Base Sub New() Static sl As Integer = 10 Console.WriteLine(sl.ToString) sl += 1 End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 1 10]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_WithFields() 'The Use of Static Locals within shared methods with same name as static local in each method Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public sl = 10 Public Sub Main() 'These should touch the static locals testMethod() testMethod2(True) testMethod() testMethod2(True) testMethod() testMethod2(True) 'These should touch the field - sl out of scope in method testMethod2(False) testMethod2(False) testMethod2(False) 'These should touch the static locals as SL declaration moved ins cope for both code blocks testMethod3(True) testMethod3(False) testMethod3(True) testMethod3(False) testMethod3(True) testMethod3(False) End Sub Sub testMethod() Static sl As Integer = 1 sl += 1 Console.WriteLine(sl.ToString) End Sub Sub testMethod2(x As Boolean) 'Only true in Scope for Static Local, False is field If x = True Then Static sl As Integer = 1 sl += 1 Console.WriteLine(sl.ToString) Else sl += 1 Console.WriteLine(sl.ToString) End If End Sub Sub testMethod3(x As Boolean) 'Both Code Blocks in Scope for Static Local Static sl As Integer = 1 If sl = True Then sl += 1 Console.WriteLine(sl.ToString) Else sl += 1 Console.WriteLine(sl.ToString) End If End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[2 2 3 3 4 4 11 12 13 2 3 4 5 6 7]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_WithProperty() 'The Use of Static Locals within shared methods with same name as static local in each method Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Property sl = 10 Public Sub Main() 'These should touch the static locals testMethod() testMethod2(True) testMethod() testMethod2(True) testMethod() testMethod2(True) 'These should touch the field - sl out of scope in method testMethod2(False) testMethod2(False) testMethod2(False) 'These should touch the static locals as SL declaration moved ins cope for both code blocks testMethod3(True) testMethod3(False) testMethod3(True) testMethod3(False) testMethod3(True) testMethod3(False) End Sub Sub testMethod() Static sl As Integer = 1 sl += 1 Console.WriteLine(sl.ToString) End Sub Sub testMethod2(x As Boolean) 'Only true in Scope for Static Local, False is field If x = True Then Static sl As Integer = 1 sl += 1 Console.WriteLine(sl.ToString) Else sl += 1 Console.WriteLine(sl.ToString) End If End Sub Sub testMethod3(x As Boolean) 'Both Code Blocks in Scope for Static Local Static sl As Integer = 1 If sl = True Then sl += 1 Console.WriteLine(sl.ToString) Else sl += 1 Console.WriteLine(sl.ToString) End If End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[2 2 3 3 4 4 11 12 13 2 3 4 5 6 7]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_InPropertySetter() 'The Use of Static Locals within shared methods with same name as static local in each method Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() 'Each time I set property sl should increment Dim obj1 As New Goo obj1.sl = 1 obj1.sl = 2 obj1.sl = 3 'Different Object Dim Obj2 As New Goo With {.sl = 1} Obj2.sl = 2 End Sub Class Goo Public _field As Integer = 0 Public Property sl As Integer Set(value As Integer) Static sl As Integer = 1 Console.WriteLine(sl.ToString) sl += 1 _field = value End Set Get Return _field End Get End Property End Class End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 3 1 2]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_InConstructor() 'The Use of Static Locals within Constructor Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Dim obj1 As New Goo Dim obj2 As New Goo Dim obj3 As New Goo End Sub Class Goo Sub New() Static sl As Integer = 1 Console.WriteLine(sl.ToString) sl += 1 End Sub End Class End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 1 1]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_InSharedConstructor() 'The Use of Static Locals within Shared Constructor - Only called Once Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Dim obj1 As New Goo Dim obj2 As New Goo Dim obj3 As New Goo End Sub Class Goo Shared Sub New() Static sl As Integer = 1 Console.WriteLine(sl.ToString) sl += 1 End Sub End Class End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")> Public Sub Semantic_InFinalizer() 'The Use of Static Locals within Finalizer - No Problems Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Dim x As New TestClass End Sub End Module Class TestClass Sub New() Static SLConstructor As Integer = 1 End Sub Protected Overrides Sub Finalize() Static SLFinalize As Integer = 1 Console.WriteLine(SLFinalize.ToString) MyBase.Finalize() End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) compilationDef.VerifyDiagnostics() End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_MaximumLength_StaticLocalIdentifier() 'The Use of Static Locals with an identifier at maxmimum length to ensure functionality 'works and generated backing field is correctly supported. Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() MaximumLengthIdentifierIn2012() MaximumLengthIdentifierIn2012() MaximumLengthIdentifierIn2012() End Sub Sub MaximumLengthIdentifierIn2012() Static abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk As Integer = 1 Console.WriteLine(abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk.ToString) abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk += 1 End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 3]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalPartialClasses() 'Ensure that the code generated field is correctly generated in Partial Class / Partial Private scenarios Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Test() End Sub Sub test() Dim x As New P1 x.Caller() x.Caller() x.Caller() End Sub End Module Partial Class P1 Public Sub Caller() Goo() End Sub Partial Private Sub Goo() End Sub End Class Partial Class P1 Private Sub Goo() Static i As Integer = 1 Console.WriteLine(i.ToString) i += 1 End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 3]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub semanticInfo_StaticKeywordOnly_IsStatic() Dim source = <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Goo() Goo() End Sub Sub Goo() Static x As Long = 2 Console.WriteLine(x.ToString) x += 1 'BIND:"x" End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim tree = compilation.SyntaxTrees(0) Dim treeModel = compilation.GetSemanticModel(tree) Dim cDecl = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.LocalDeclarationStatement, 1).AsNode(), LocalDeclarationStatementSyntax) Dim cTypeSymbol = treeModel.GetSemanticInfoSummary(DirectCast(cDecl.Declarators(0).AsClause, SimpleAsClauseSyntax).Type).Type Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Dim iSymbol = DirectCast(semanticInfo.Symbol, LocalSymbol) Assert.True(iSymbol.IsStatic) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub semanticInfo_StaticAndDimKeyword_IsStatic() Dim source = <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Goo() Goo() End Sub Sub Goo() Static Dim x As Long = 2 Console.WriteLine(x.ToString) x += 1 'BIND:"x" End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim tree = compilation.SyntaxTrees(0) Dim treeModel = compilation.GetSemanticModel(tree) Dim cDecl = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.LocalDeclarationStatement, 1).AsNode(), LocalDeclarationStatementSyntax) Dim cTypeSymbol = treeModel.GetSemanticInfoSummary(DirectCast(cDecl.Declarators(0).AsClause, SimpleAsClauseSyntax).Type).Type Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Dim iSymbol = DirectCast(semanticInfo.Symbol, LocalSymbol) Assert.True(iSymbol.IsStatic) source = <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Goo() Goo() End Sub Sub Goo() Dim Static x As Long = 2 Console.WriteLine(x.ToString) x += 1 'BIND:"x" End Sub End Module </file> </compilation> compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) tree = compilation.SyntaxTrees(0) treeModel = compilation.GetSemanticModel(tree) cDecl = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.LocalDeclarationStatement, 1).AsNode(), LocalDeclarationStatementSyntax) cTypeSymbol = treeModel.GetSemanticInfoSummary(DirectCast(cDecl.Declarators(0).AsClause, SimpleAsClauseSyntax).Type).Type semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") iSymbol = DirectCast(semanticInfo.Symbol, LocalSymbol) Assert.True(iSymbol.IsStatic) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub semanticInfo_StaticDimOnly_IsStatic() Dim source = <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Goo() Goo() End Sub Sub Goo() Dim x As Long = 2 Console.WriteLine(x.ToString) x += 1 'BIND:"x" End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim tree = compilation.SyntaxTrees(0) Dim treeModel = compilation.GetSemanticModel(tree) Dim cDecl = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.LocalDeclarationStatement, 1).AsNode(), LocalDeclarationStatementSyntax) Dim cTypeSymbol = treeModel.GetSemanticInfoSummary(DirectCast(cDecl.Declarators(0).AsClause, SimpleAsClauseSyntax).Type).Type Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Dim iSymbol = DirectCast(semanticInfo.Symbol, LocalSymbol) Assert.False(iSymbol.IsStatic) 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 Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class StaticLocalsSemanticTests Inherits BasicTestBase <Fact, WorkItem(15925, "DevDiv_Projects/Roslyn")> Public Sub Semantic_StaticLocalDeclarationInSub() Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class Module1 Public Shared Sub Main() StaticLocalInSub() StaticLocalInSub() End Sub Shared Sub StaticLocalInSub() Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[StaticLocalInSub System.Int32 1 StaticLocalInSub System.Int32 2]]>) End Sub <Fact, WorkItem(15925, "DevDiv_Projects/Roslyn")> Public Sub Semantic_StaticLocalDeclarationInSubModule() Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() StaticLocalInSub() StaticLocalInSub() End Sub Sub StaticLocalInSub() Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[StaticLocalInSub System.Int32 1 StaticLocalInSub System.Int32 2]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclarationInFunction() 'Using different Type as well Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Dim x1 = StaticLocalInFunction() x1 = StaticLocalInFunction() End Sub Function StaticLocalInFunction() As Long Static SLItem1 As Long = 1 'Type Character Console.WriteLine("StaticLocalInFunction") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 Return SLItem1 End Function End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[StaticLocalInFunction System.Int64 1 StaticLocalInFunction System.Int64 2]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclarationReferenceType() Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() StaticLocalRefType() StaticLocalRefType() StaticLocalRefType() End Sub Sub StaticLocalRefType() Static SLItem1 As String = "" SLItem1 &amp;= "*" Console.WriteLine("StaticLocalRefType") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[StaticLocalRefType System.String * StaticLocalRefType System.String ** StaticLocalRefType System.String ***]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclarationUserDefinedClass() 'With a user defined reference type (class) this should only initialize on initial invocation and then 'increment each time Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() StaticLocalUserDefinedType() StaticLocalUserDefinedType() StaticLocalUserDefinedType() End Sub Sub StaticLocalUserDefinedType() Static SLi As Integer = 1 Static SLItem1 As TestUDClass = New TestUDClass With {.ABC = SLi} SLItem1.ABC = SLi SLi += 1 Console.WriteLine("StaticLocalUserDefinedType") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value Console.WriteLine(SLItem1.ABC.ToString) 'Value End Sub End Module Class TestUDClass Public Property ABC As Integer = 1 End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[StaticLocalUserDefinedType TestUDClass TestUDClass 1 StaticLocalUserDefinedType TestUDClass TestUDClass 2 StaticLocalUserDefinedType TestUDClass TestUDClass 3 ]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclaration_InGenericType() 'Can declare in generic type, just not in generic method Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Dim x As New UDTest(Of Integer) x.Goo() x.Goo() x.Goo() End Sub End Module Public Class UDTest(Of t) Public Sub Goo() Static SLItem As Integer = 1 Console.WriteLine(SLItem.ToString) SLItem += 1 End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 3]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclaration_Keyword_NameClashInType() 'declare Escaped identifier called static Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() AvoidingNameConflicts() AvoidingNameConflicts() AvoidingNameConflicts() End Sub Sub AvoidingNameConflicts() Static [Static] As Integer = 1 Console.WriteLine([Static]) [Static] += 1 End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 3]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclaration_Keyword_NameClashEscaped() 'declare identifier and type called static both of which need to be escaped along with static Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() AvoidingNameConflicts() AvoidingNameConflicts() AvoidingNameConflicts() End Sub Sub AvoidingNameConflicts() Static [Static] As [Static] = New [Static] With {.ABC = 1} Console.WriteLine([Static].ABC) [Static].ABC += 1 End Sub End Module Class [Static] Public Property ABC As Integer End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 3]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclaration_Keyword_NameClash_Property_NoEscapingRequired() 'declare Property called static doesnt need escaping because of preceding . Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() AvoidingNameConflicts() AvoidingNameConflicts() AvoidingNameConflicts() End Sub Sub AvoidingNameConflicts() Static S1 As [Static] = New [Static] With {.Static = 1} Console.WriteLine(S1.Static) S1.Static += 1 End Sub End Module Class [Static] Public Property [Static] As Integer End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 3]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclaration_LateBound() ' test late bind ' call ToString() on object defeat the purpose Dim currCulture = Threading.Thread.CurrentThread.CurrentCulture Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture Try 'Declare static local which is late bound Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() WithTypeObject(1) WithTypeObject(2) WithTypeObject(3) End Sub Sub WithTypeObject(x As Integer) Static sl1 As Object = 1 Console.WriteLine("Prior:" &amp; sl1) Select Case x Case 1 sl1 = 1 Case 2 sl1 = "Test" Case Else sl1 = 5.5 End Select Console.WriteLine("After:" &amp; sl1) End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[Prior:1 After:1 Prior:1 After:Test Prior:Test After:5.5]]>) Catch ex As Exception Assert.Null(ex) Finally Threading.Thread.CurrentThread.CurrentCulture = currCulture End Try End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclaration_WithTypeCharacters() 'Declare static local using type identifier Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() WithTypeCharacters() WithTypeCharacters() WithTypeCharacters() End Sub Sub WithTypeCharacters() Static sl1% = 1 'integer Static sl2&amp; = 1 'Long Static sl3@ = 1 'Decimal Static sl4! = 1 'Single Static sl5# = 1 'Double Static sl6$ = "" 'String Console.WriteLine(sl1) Console.WriteLine(sl2) Console.WriteLine(sl3) Console.WriteLine(sl4.ToString(System.Globalization.CultureInfo.InvariantCulture)) Console.WriteLine(sl5.ToString(System.Globalization.CultureInfo.InvariantCulture)) Console.WriteLine(sl6) sl1 +=1 sl2 +=1 sl3 +=1 sl4 +=0.5 sl5 +=0.5 sl6 +="*" End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 1 1 1 1 2 2 2 1.5 1.5 * 3 3 3 2 2 **]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclaration_WithArrayTypes() 'Declare static local with array types Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() WithArrayType() WithArrayType() End Sub Sub WithArrayType() Static Dim sl1 As Integer() = {1, 2, 3} 'integer 'Show Values Console.WriteLine(sl1.Length) For Each i In sl1 Console.Write(i.ToString &amp; " ") Next Console.WriteLine("") sl1 = {11, 12} End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[3 1 2 3 2 11 12]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclaration_WithCollectionInitializer() 'Declare static local using collection types / extension methods and the Add would be invoked each time, Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System 'Used my own attribute for Extension attribute based upon necessary signature rather than adding a specific reference to 'System.Core which contains this normally Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method, AllowMultiple:=False, Inherited:=False)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace Public Module Module1 Public Sub Main() Dim x As New System.Collections.Generic.Stack(Of Integer) From {11, 21, 31} End Sub &lt;System.Runtime.CompilerServices.Extension&gt; Public Sub Add(x As System.Collections.Generic.Stack(Of Integer), y As Integer) Static Dim sl1 As Integer = 0 sl1 += 1 Console.WriteLine(sl1.ToString &amp; " Value:" &amp; y.ToString) x.Push(y) End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 Value:11 2 Value:21 3 Value:31]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclaration_WithDim() 'Declare static local in conjunction with a Dim keyword Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() WithTypeCharacters() WithTypeCharacters() WithTypeCharacters() End Sub Sub WithTypeCharacters() Static Dim sl1 As Integer = 1 'integer Console.WriteLine(sl1) sl1 += 1 End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 3]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalDeclaration_WithAttribute() 'This is important because the static local can have an attribute on it whereas a normal local cannot ParseAndVerify(<![CDATA[ Imports System Public Module Module1 Public Sub Main() Goo() Goo() Goo() End Sub Sub Goo() <Test> Static a1 As Integer = 1 a1 += 1 Console.WriteLine(a1.ToString) End Sub End Module <AttributeUsage(AttributeTargets.All)> Class TestAttribute Inherits Attribute End Class ]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalInTryCatchBlock() 'The Use of Static Locals within Try/Catch/Finally Blocks 'Simple Usage Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() CatchBlock() CatchBlock() FinallyBlock() FinallyBlock() NotCalledCatchBlock() NotCalledCatchBlock() End Sub Sub CatchBlock() Try Throw New Exception Catch ex As Exception Static a As Integer = 1 Console.WriteLine(a.ToString) a += 1 End Try End Sub Sub FinallyBlock() Try Throw New Exception Catch ex As Exception Finally Static a As Integer = 1 Console.WriteLine(a.ToString) a += 1 End Try End Sub Sub NotCalledCatchBlock() Try Catch ex As Exception Static a As Integer = 1 Console.WriteLine(a.ToString) a += 1 End Try End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 1 2]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalExceptionInInitialization() Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public ExceptionThrow As Boolean = False Public Sub Main() ExceptionThrow = False test(True) 'First Time Exception thrown so it will result in static local initialized to default for second call If ExceptionThrow Then Console.WriteLine("Exception Thrown") Else Console.WriteLine("No Exception Thrown") ExceptionThrow = False test(True) 'This should result in value of default value +1 and no exception thrown on second invocation If ExceptionThrow Then Console.WriteLine("Exception Thrown") Else Console.WriteLine("No Exception Thrown") ExceptionThrow = False test(True) 'This should result in value of default value +1 and no exception thrown on second invocation If ExceptionThrow Then Console.WriteLine("Exception Thrown") Else Console.WriteLine("No Exception Thrown") End Sub Sub test(BlnThrowException As Boolean) Try Static sl As Integer = throwException(BlnThrowException) 'Something to cause exception sl += 1 Console.WriteLine(sl.ToString) Catch ex As Exception ExceptionThrow = True Finally End Try End Sub Function throwException(x As Boolean) As Integer If x = True Then Throw New Exception Else Return 1 End If End Function End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[ Exception Thrown 1 No Exception Thrown 2 No Exception Thrown]]>) 'SemanticInfoTypeTestForeach(compilation1, 1, "String()", "System.Collections.IEnumerable") 'AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="s", ReadInsideSymbol:="arr, s", ReadOutsideSymbol:="arr", ' WrittenInsideSymbol:="s", WrittenOutsideSymbol:="arr", ' AlwaysAssignedSymbol:="", DataFlowsInSymbol:="arr", DataFlowsOutSymbol:="") 'AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, ' EndPointIsReachable:=True) 'ClassfiConversionTestForeach(compilation1) 'VerifyForeachSemanticInfo(compilation1) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalInTryCatchBlock_21() 'The Use of Static Locals within Try/Catch/Finally Blocks Dim compilationDef = <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() test(False) test(True) test(False) End Sub Sub test(ThrowException As Boolean) Static sl As Integer = 1 Try If ThrowException Then Throw New Exception End If Catch ex As Exception sl += 1 End Try Console.WriteLine(sl.ToString) End Sub End Module End Module </file> </compilation> 'Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndVBRuntime(compilationDef) 'compilation.VerifyDiagnostics() End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalInTryCatchBlock_3() 'The Use of Static Locals within Try/Catch/Finally Blocks Dim compilationDef = <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() test(True) test(False) test(True) End Sub Sub test(ThrowException As Boolean) Static sl As Integer = 1 Try If ThrowException Then Throw New Exception End If Catch ex As Exception sl += 1 End Try Console.WriteLine(sl.ToString) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics() End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalInTryCatchFinallyBlock() 'The Use of Static Locals within Try/Catch/Finally Blocks Dim compilationDef = <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() CatchBlock() CatchBlock() FinallyBlock() FinallyBlock() NotCalledCatchBlock() NotCalledCatchBlock() End Sub Sub CatchBlock() Try Throw New Exception Catch ex As Exception Static a As Integer = 1 Console.WriteLine(a.ToString) a += 1 End Try End Sub Sub FinallyBlock() Try Throw New Exception Catch ex As Exception Finally Static a As Integer = 1 Console.WriteLine(a.ToString) a += 1 End Try End Sub Sub NotCalledCatchBlock() Try Catch ex As Exception Static a As Integer = 1 Console.WriteLine(a.ToString) a += 1 End Try End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 1 2]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalInTryCatchBlock_2() 'The Use of Static Locals within Try/Catch/Finally Blocks Dim compilationDef = <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() test(False) test(True) test(False) End Sub Sub test(ThrowException As Boolean) Static sl As Integer = 1 Try If ThrowException Then Throw New Exception End If Catch ex As Exception sl += 1 End Try Console.WriteLine(sl.ToString) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 2]]>) End Sub Public Sub Semantic_SameNameInDifferentMethods() 'The Use of Static Locals within shared methods with same name as static local in each method Dim compilationDef = <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Test1() Test2() Test1() Test2() End Sub Sub Test1() Static sl As Integer = 1 Console.WriteLine(sl.ToString) sl += 1 End Sub Sub Test2() Static sl As Integer = 1 Console.WriteLine(sl.ToString) sl += 1 End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 1 2 2]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_SameNameInDifferentOverloads() 'The Use of Static Locals within shared methods with same name as static local in each method Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Test() Test(1) Test() Test(1) End Sub Sub Test() Static sl As Integer = 1 Console.WriteLine(sl.ToString) sl += 1 End Sub Sub Test(x As Integer) Static sl As Integer = 1 Console.WriteLine(sl.ToString) sl += 1 End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 1 2 2]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_SharedMethods() 'The Use of Static Locals within shared methods with same name as static local in each method Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C1 Public Shared Sub Main() testMethod() testMethod2() testMethod() testMethod2() testMethod() testMethod2() End Sub Shared Sub testMethod() Static sl As Integer = 1 sl += 1 Console.WriteLine(sl.ToString) End Sub Shared Sub testMethod2() Static sl As Integer = 1 sl += 1 Console.WriteLine(sl.ToString) End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[2 2 3 3 4 4]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_OverriddenMethod() 'The Use of Static Locals in both a base and derived class with overridden method Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Dim Obj As New Base Obj.Goo() Obj.Goo() Obj.Goo() Dim ObjD As New Derived ObjD.goo() ObjD.goo() ObjD.goo() End Sub End Module Class Base Overridable Sub Goo() Static sl As Integer = 1 Console.WriteLine(sl.ToString) sl += 1 End Sub End Class Class Derived Sub goo() Static sl As Integer = 10 Console.WriteLine(sl.ToString) sl += 1 End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 3 10 11 12]]>) End Sub Public Sub Semantic_InheritanceConstructor() 'The Use of Static Locals in both a base and derived class constructor - instance method Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Dim Obj As New Base Dim ObjD As New Derived End Sub End Module Class Base Sub New() Static sl As Integer = 1 Console.WriteLine(sl.ToString) sl += 1 End Sub End Class Class Derived Inherits Base Sub New() Static sl As Integer = 10 Console.WriteLine(sl.ToString) sl += 1 End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 1 10]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_WithFields() 'The Use of Static Locals within shared methods with same name as static local in each method Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public sl = 10 Public Sub Main() 'These should touch the static locals testMethod() testMethod2(True) testMethod() testMethod2(True) testMethod() testMethod2(True) 'These should touch the field - sl out of scope in method testMethod2(False) testMethod2(False) testMethod2(False) 'These should touch the static locals as SL declaration moved ins cope for both code blocks testMethod3(True) testMethod3(False) testMethod3(True) testMethod3(False) testMethod3(True) testMethod3(False) End Sub Sub testMethod() Static sl As Integer = 1 sl += 1 Console.WriteLine(sl.ToString) End Sub Sub testMethod2(x As Boolean) 'Only true in Scope for Static Local, False is field If x = True Then Static sl As Integer = 1 sl += 1 Console.WriteLine(sl.ToString) Else sl += 1 Console.WriteLine(sl.ToString) End If End Sub Sub testMethod3(x As Boolean) 'Both Code Blocks in Scope for Static Local Static sl As Integer = 1 If sl = True Then sl += 1 Console.WriteLine(sl.ToString) Else sl += 1 Console.WriteLine(sl.ToString) End If End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[2 2 3 3 4 4 11 12 13 2 3 4 5 6 7]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_WithProperty() 'The Use of Static Locals within shared methods with same name as static local in each method Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Property sl = 10 Public Sub Main() 'These should touch the static locals testMethod() testMethod2(True) testMethod() testMethod2(True) testMethod() testMethod2(True) 'These should touch the field - sl out of scope in method testMethod2(False) testMethod2(False) testMethod2(False) 'These should touch the static locals as SL declaration moved ins cope for both code blocks testMethod3(True) testMethod3(False) testMethod3(True) testMethod3(False) testMethod3(True) testMethod3(False) End Sub Sub testMethod() Static sl As Integer = 1 sl += 1 Console.WriteLine(sl.ToString) End Sub Sub testMethod2(x As Boolean) 'Only true in Scope for Static Local, False is field If x = True Then Static sl As Integer = 1 sl += 1 Console.WriteLine(sl.ToString) Else sl += 1 Console.WriteLine(sl.ToString) End If End Sub Sub testMethod3(x As Boolean) 'Both Code Blocks in Scope for Static Local Static sl As Integer = 1 If sl = True Then sl += 1 Console.WriteLine(sl.ToString) Else sl += 1 Console.WriteLine(sl.ToString) End If End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[2 2 3 3 4 4 11 12 13 2 3 4 5 6 7]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_InPropertySetter() 'The Use of Static Locals within shared methods with same name as static local in each method Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() 'Each time I set property sl should increment Dim obj1 As New Goo obj1.sl = 1 obj1.sl = 2 obj1.sl = 3 'Different Object Dim Obj2 As New Goo With {.sl = 1} Obj2.sl = 2 End Sub Class Goo Public _field As Integer = 0 Public Property sl As Integer Set(value As Integer) Static sl As Integer = 1 Console.WriteLine(sl.ToString) sl += 1 _field = value End Set Get Return _field End Get End Property End Class End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 3 1 2]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_InConstructor() 'The Use of Static Locals within Constructor Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Dim obj1 As New Goo Dim obj2 As New Goo Dim obj3 As New Goo End Sub Class Goo Sub New() Static sl As Integer = 1 Console.WriteLine(sl.ToString) sl += 1 End Sub End Class End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 1 1]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_InSharedConstructor() 'The Use of Static Locals within Shared Constructor - Only called Once Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Dim obj1 As New Goo Dim obj2 As New Goo Dim obj3 As New Goo End Sub Class Goo Shared Sub New() Static sl As Integer = 1 Console.WriteLine(sl.ToString) sl += 1 End Sub End Class End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")> Public Sub Semantic_InFinalizer() 'The Use of Static Locals within Finalizer - No Problems Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Dim x As New TestClass End Sub End Module Class TestClass Sub New() Static SLConstructor As Integer = 1 End Sub Protected Overrides Sub Finalize() Static SLFinalize As Integer = 1 Console.WriteLine(SLFinalize.ToString) MyBase.Finalize() End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) compilationDef.VerifyDiagnostics() End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_MaximumLength_StaticLocalIdentifier() 'The Use of Static Locals with an identifier at maxmimum length to ensure functionality 'works and generated backing field is correctly supported. Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() MaximumLengthIdentifierIn2012() MaximumLengthIdentifierIn2012() MaximumLengthIdentifierIn2012() End Sub Sub MaximumLengthIdentifierIn2012() Static abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk As Integer = 1 Console.WriteLine(abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk.ToString) abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk += 1 End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 3]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Semantic_StaticLocalPartialClasses() 'Ensure that the code generated field is correctly generated in Partial Class / Partial Private scenarios Dim compilationDef = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Test() End Sub Sub test() Dim x As New P1 x.Caller() x.Caller() x.Caller() End Sub End Module Partial Class P1 Public Sub Caller() Goo() End Sub Partial Private Sub Goo() End Sub End Class Partial Class P1 Private Sub Goo() Static i As Integer = 1 Console.WriteLine(i.ToString) i += 1 End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[1 2 3]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub semanticInfo_StaticKeywordOnly_IsStatic() Dim source = <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Goo() Goo() End Sub Sub Goo() Static x As Long = 2 Console.WriteLine(x.ToString) x += 1 'BIND:"x" End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim tree = compilation.SyntaxTrees(0) Dim treeModel = compilation.GetSemanticModel(tree) Dim cDecl = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.LocalDeclarationStatement, 1).AsNode(), LocalDeclarationStatementSyntax) Dim cTypeSymbol = treeModel.GetSemanticInfoSummary(DirectCast(cDecl.Declarators(0).AsClause, SimpleAsClauseSyntax).Type).Type Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Dim iSymbol = DirectCast(semanticInfo.Symbol, LocalSymbol) Assert.True(iSymbol.IsStatic) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub semanticInfo_StaticAndDimKeyword_IsStatic() Dim source = <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Goo() Goo() End Sub Sub Goo() Static Dim x As Long = 2 Console.WriteLine(x.ToString) x += 1 'BIND:"x" End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim tree = compilation.SyntaxTrees(0) Dim treeModel = compilation.GetSemanticModel(tree) Dim cDecl = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.LocalDeclarationStatement, 1).AsNode(), LocalDeclarationStatementSyntax) Dim cTypeSymbol = treeModel.GetSemanticInfoSummary(DirectCast(cDecl.Declarators(0).AsClause, SimpleAsClauseSyntax).Type).Type Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Dim iSymbol = DirectCast(semanticInfo.Symbol, LocalSymbol) Assert.True(iSymbol.IsStatic) source = <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Goo() Goo() End Sub Sub Goo() Dim Static x As Long = 2 Console.WriteLine(x.ToString) x += 1 'BIND:"x" End Sub End Module </file> </compilation> compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) tree = compilation.SyntaxTrees(0) treeModel = compilation.GetSemanticModel(tree) cDecl = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.LocalDeclarationStatement, 1).AsNode(), LocalDeclarationStatementSyntax) cTypeSymbol = treeModel.GetSemanticInfoSummary(DirectCast(cDecl.Declarators(0).AsClause, SimpleAsClauseSyntax).Type).Type semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") iSymbol = DirectCast(semanticInfo.Symbol, LocalSymbol) Assert.True(iSymbol.IsStatic) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub semanticInfo_StaticDimOnly_IsStatic() Dim source = <compilation> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() Goo() Goo() End Sub Sub Goo() Dim x As Long = 2 Console.WriteLine(x.ToString) x += 1 'BIND:"x" End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim tree = compilation.SyntaxTrees(0) Dim treeModel = compilation.GetSemanticModel(tree) Dim cDecl = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.LocalDeclarationStatement, 1).AsNode(), LocalDeclarationStatementSyntax) Dim cTypeSymbol = treeModel.GetSemanticInfoSummary(DirectCast(cDecl.Declarators(0).AsClause, SimpleAsClauseSyntax).Type).Type Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Dim iSymbol = DirectCast(semanticInfo.Symbol, LocalSymbol) Assert.False(iSymbol.IsStatic) End Sub End Class End Namespace
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/SyntaxGeneratorInternalExtensions/SyntaxGeneratorInternal.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.Editing { /// <summary> /// Internal extensions to <see cref="SyntaxGenerator"/>. /// /// This interface is available in the shared CodeStyle and Workspaces layer to allow /// sharing internal generator methods between them. Once the methods are ready to be /// made public APIs, they can be moved to <see cref="SyntaxGenerator"/>. /// </summary> internal abstract class SyntaxGeneratorInternal : ILanguageService { internal abstract ISyntaxFacts SyntaxFacts { get; } internal abstract SyntaxTrivia EndOfLine(string text); /// <summary> /// Creates a statement that declares a single local variable with an optional initializer. /// </summary> internal abstract SyntaxNode LocalDeclarationStatement( SyntaxNode type, SyntaxToken identifier, SyntaxNode initializer = null, bool isConst = false); /// <summary> /// Creates a statement that declares a single local variable. /// </summary> internal SyntaxNode LocalDeclarationStatement(SyntaxToken name, SyntaxNode initializer) => LocalDeclarationStatement(null, name, initializer); internal abstract SyntaxNode WithInitializer(SyntaxNode variableDeclarator, SyntaxNode initializer); internal abstract SyntaxNode EqualsValueClause(SyntaxToken operatorToken, SyntaxNode value); internal abstract SyntaxToken Identifier(string identifier); internal abstract SyntaxNode ConditionalAccessExpression(SyntaxNode expression, SyntaxNode whenNotNull); internal abstract SyntaxNode MemberBindingExpression(SyntaxNode name); internal abstract SyntaxNode RefExpression(SyntaxNode expression); /// <summary> /// Wraps with parens. /// </summary> internal abstract SyntaxNode AddParentheses(SyntaxNode expression, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true); /// <summary> /// Creates a statement that can be used to yield a value from an iterator method. /// </summary> /// <param name="expression">An expression that can be yielded.</param> internal abstract SyntaxNode YieldReturnStatement(SyntaxNode expression); /// <summary> /// <see langword="true"/> if the language requires a "TypeExpression" /// (including <see langword="var"/>) to be stated when making a /// <see cref="LocalDeclarationStatement(SyntaxNode, SyntaxToken, SyntaxNode, bool)"/>. /// <see langword="false"/> if the language allows the type node to be entirely elided. /// </summary> internal abstract bool RequiresLocalDeclarationType(); internal abstract SyntaxToken InterpolatedStringTextToken(string content, string value); internal abstract SyntaxNode InterpolatedStringText(SyntaxToken textToken); internal abstract SyntaxNode Interpolation(SyntaxNode syntaxNode); internal abstract SyntaxNode InterpolatedStringExpression(SyntaxToken startToken, IEnumerable<SyntaxNode> content, SyntaxToken endToken); internal abstract SyntaxNode InterpolationAlignmentClause(SyntaxNode alignment); internal abstract SyntaxNode InterpolationFormatClause(string format); internal abstract SyntaxNode TypeParameterList(IEnumerable<string> typeParameterNames); /// <summary> /// Produces an appropriate TypeSyntax for the given <see cref="ITypeSymbol"/>. The <paramref name="typeContext"/> /// flag controls how this should be created depending on if this node is intended for use in a type-only /// context, or an expression-level context. In the former case, both C# and VB will create QualifiedNameSyntax /// nodes for dotted type names, whereas in the latter case both languages will create MemberAccessExpressionSyntax /// nodes. The final stringified result will be the same in both cases. However, the structure of the trees /// will be substantively different, which can impact how the compilation layers analyze the tree and how /// transformational passes affect it. /// </summary> /// <remarks> /// Passing in the right value for <paramref name="typeContext"/> is necessary for correctness and for use /// of compilation (and other) layers in a supported fashion. For example, if a QualifiedTypeSyntax is /// sed in a place the compiler would have parsed out a MemberAccessExpression, then it is undefined behavior /// what will happen if that tree is passed to any other components. /// </remarks> internal abstract SyntaxNode Type(ITypeSymbol typeSymbol, bool typeContext); #region Patterns internal abstract bool SupportsPatterns(ParseOptions options); internal abstract SyntaxNode IsPatternExpression(SyntaxNode expression, SyntaxToken isToken, SyntaxNode pattern); internal abstract SyntaxNode AndPattern(SyntaxNode left, SyntaxNode right); internal abstract SyntaxNode DeclarationPattern(INamedTypeSymbol type, string name); internal abstract SyntaxNode ConstantPattern(SyntaxNode expression); internal abstract SyntaxNode NotPattern(SyntaxNode pattern); internal abstract SyntaxNode OrPattern(SyntaxNode left, SyntaxNode right); internal abstract SyntaxNode ParenthesizedPattern(SyntaxNode pattern); internal abstract SyntaxNode TypePattern(SyntaxNode type); #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 Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.Editing { /// <summary> /// Internal extensions to <see cref="SyntaxGenerator"/>. /// /// This interface is available in the shared CodeStyle and Workspaces layer to allow /// sharing internal generator methods between them. Once the methods are ready to be /// made public APIs, they can be moved to <see cref="SyntaxGenerator"/>. /// </summary> internal abstract class SyntaxGeneratorInternal : ILanguageService { internal abstract ISyntaxFacts SyntaxFacts { get; } internal abstract SyntaxTrivia EndOfLine(string text); /// <summary> /// Creates a statement that declares a single local variable with an optional initializer. /// </summary> internal abstract SyntaxNode LocalDeclarationStatement( SyntaxNode type, SyntaxToken identifier, SyntaxNode initializer = null, bool isConst = false); /// <summary> /// Creates a statement that declares a single local variable. /// </summary> internal SyntaxNode LocalDeclarationStatement(SyntaxToken name, SyntaxNode initializer) => LocalDeclarationStatement(null, name, initializer); internal abstract SyntaxNode WithInitializer(SyntaxNode variableDeclarator, SyntaxNode initializer); internal abstract SyntaxNode EqualsValueClause(SyntaxToken operatorToken, SyntaxNode value); internal abstract SyntaxToken Identifier(string identifier); internal abstract SyntaxNode ConditionalAccessExpression(SyntaxNode expression, SyntaxNode whenNotNull); internal abstract SyntaxNode MemberBindingExpression(SyntaxNode name); internal abstract SyntaxNode RefExpression(SyntaxNode expression); /// <summary> /// Wraps with parens. /// </summary> internal abstract SyntaxNode AddParentheses(SyntaxNode expression, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true); /// <summary> /// Creates a statement that can be used to yield a value from an iterator method. /// </summary> /// <param name="expression">An expression that can be yielded.</param> internal abstract SyntaxNode YieldReturnStatement(SyntaxNode expression); /// <summary> /// <see langword="true"/> if the language requires a "TypeExpression" /// (including <see langword="var"/>) to be stated when making a /// <see cref="LocalDeclarationStatement(SyntaxNode, SyntaxToken, SyntaxNode, bool)"/>. /// <see langword="false"/> if the language allows the type node to be entirely elided. /// </summary> internal abstract bool RequiresLocalDeclarationType(); internal abstract SyntaxToken InterpolatedStringTextToken(string content, string value); internal abstract SyntaxNode InterpolatedStringText(SyntaxToken textToken); internal abstract SyntaxNode Interpolation(SyntaxNode syntaxNode); internal abstract SyntaxNode InterpolatedStringExpression(SyntaxToken startToken, IEnumerable<SyntaxNode> content, SyntaxToken endToken); internal abstract SyntaxNode InterpolationAlignmentClause(SyntaxNode alignment); internal abstract SyntaxNode InterpolationFormatClause(string format); internal abstract SyntaxNode TypeParameterList(IEnumerable<string> typeParameterNames); /// <summary> /// Produces an appropriate TypeSyntax for the given <see cref="ITypeSymbol"/>. The <paramref name="typeContext"/> /// flag controls how this should be created depending on if this node is intended for use in a type-only /// context, or an expression-level context. In the former case, both C# and VB will create QualifiedNameSyntax /// nodes for dotted type names, whereas in the latter case both languages will create MemberAccessExpressionSyntax /// nodes. The final stringified result will be the same in both cases. However, the structure of the trees /// will be substantively different, which can impact how the compilation layers analyze the tree and how /// transformational passes affect it. /// </summary> /// <remarks> /// Passing in the right value for <paramref name="typeContext"/> is necessary for correctness and for use /// of compilation (and other) layers in a supported fashion. For example, if a QualifiedTypeSyntax is /// sed in a place the compiler would have parsed out a MemberAccessExpression, then it is undefined behavior /// what will happen if that tree is passed to any other components. /// </remarks> internal abstract SyntaxNode Type(ITypeSymbol typeSymbol, bool typeContext); #region Patterns internal abstract bool SupportsPatterns(ParseOptions options); internal abstract SyntaxNode IsPatternExpression(SyntaxNode expression, SyntaxToken isToken, SyntaxNode pattern); internal abstract SyntaxNode AndPattern(SyntaxNode left, SyntaxNode right); internal abstract SyntaxNode DeclarationPattern(INamedTypeSymbol type, string name); internal abstract SyntaxNode ConstantPattern(SyntaxNode expression); internal abstract SyntaxNode NotPattern(SyntaxNode pattern); internal abstract SyntaxNode OrPattern(SyntaxNode left, SyntaxNode right); internal abstract SyntaxNode ParenthesizedPattern(SyntaxNode pattern); internal abstract SyntaxNode TypePattern(SyntaxNode type); #endregion } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/CodeFixCategory.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.CodeFixes { /// <summary> /// Code fix category for code fixes provided by a <see cref="CodeFixProvider"/>. /// </summary> internal enum CodeFixCategory { /// <summary> /// Fixes code to adhere to code style. /// </summary> CodeStyle, /// <summary> /// Fixes code to improve code quality. /// </summary> CodeQuality, /// <summary> /// Fixes code to fix compiler diagnostics. /// </summary> Compile, /// <summary> /// Custom category for fix. /// </summary> 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. namespace Microsoft.CodeAnalysis.CodeFixes { /// <summary> /// Code fix category for code fixes provided by a <see cref="CodeFixProvider"/>. /// </summary> internal enum CodeFixCategory { /// <summary> /// Fixes code to adhere to code style. /// </summary> CodeStyle, /// <summary> /// Fixes code to improve code quality. /// </summary> CodeQuality, /// <summary> /// Fixes code to fix compiler diagnostics. /// </summary> Compile, /// <summary> /// Custom category for fix. /// </summary> Custom } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/VisualStudio/CSharp/Impl/CodeModel/Extenders/CodeTypeLocationExtender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; using Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Extenders { [ComVisible(true)] [ComDefaultInterface(typeof(ICSCodeTypeLocation))] public class CodeTypeLocationExtender : ICSCodeTypeLocation { internal static ICSCodeTypeLocation Create(string externalLocation) { var result = new CodeTypeLocationExtender(externalLocation); return (ICSCodeTypeLocation)ComAggregate.CreateAggregatedObject(result); } private readonly string _externalLocation; private CodeTypeLocationExtender(string externalLocation) => _externalLocation = externalLocation; public string ExternalLocation { get { return _externalLocation; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; using Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Extenders { [ComVisible(true)] [ComDefaultInterface(typeof(ICSCodeTypeLocation))] public class CodeTypeLocationExtender : ICSCodeTypeLocation { internal static ICSCodeTypeLocation Create(string externalLocation) { var result = new CodeTypeLocationExtender(externalLocation); return (ICSCodeTypeLocation)ComAggregate.CreateAggregatedObject(result); } private readonly string _externalLocation; private CodeTypeLocationExtender(string externalLocation) => _externalLocation = externalLocation; public string ExternalLocation { get { return _externalLocation; } } } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_IEqualityComparer.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.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Tagging { internal abstract partial class AbstractAsynchronousTaggerProvider<TTag> { private partial class TagSource : IEqualityComparer<ITagSpan<TTag>> { public bool Equals(ITagSpan<TTag> x, ITagSpan<TTag> y) => x.Span == y.Span && EqualityComparer<TTag>.Default.Equals(x.Tag, y.Tag); public int GetHashCode(ITagSpan<TTag> obj) => Hash.Combine(obj.Span.GetHashCode(), EqualityComparer<TTag>.Default.GetHashCode(obj.Tag)); } } }
// Licensed to the .NET Foundation under one or more 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.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Tagging { internal abstract partial class AbstractAsynchronousTaggerProvider<TTag> { private partial class TagSource : IEqualityComparer<ITagSpan<TTag>> { public bool Equals(ITagSpan<TTag> x, ITagSpan<TTag> y) => x.Span == y.Span && EqualityComparer<TTag>.Default.Equals(x.Tag, y.Tag); public int GetHashCode(ITagSpan<TTag> obj) => Hash.Combine(obj.Span.GetHashCode(), EqualityComparer<TTag>.Default.GetHashCode(obj.Tag)); } } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/EditorFeatures/Test/Diagnostics/MockDiagnosticService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { [Export(typeof(IDiagnosticService))] [Shared] [PartNotDiscoverable] internal class MockDiagnosticService : IDiagnosticService { public const string DiagnosticId = "MockId"; private DiagnosticData? _diagnostic; public event EventHandler<DiagnosticsUpdatedArgs>? DiagnosticsUpdated; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MockDiagnosticService() { } [Obsolete] public ImmutableArray<DiagnosticData> GetDiagnostics(Workspace workspace, ProjectId? projectId, DocumentId? documentId, object? id, bool includeSuppressedDiagnostics, CancellationToken cancellationToken) => GetPushDiagnosticsAsync(workspace, projectId, documentId, id, includeSuppressedDiagnostics, InternalDiagnosticsOptions.NormalDiagnosticMode, cancellationToken).AsTask().WaitAndGetResult_CanCallOnBackground(cancellationToken); public ValueTask<ImmutableArray<DiagnosticData>> GetPullDiagnosticsAsync(Workspace workspace, ProjectId? projectId, DocumentId? documentId, object? id, bool includeSuppressedDiagnostics, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) { return new ValueTask<ImmutableArray<DiagnosticData>>(GetDiagnostics(workspace, projectId, documentId)); } public ValueTask<ImmutableArray<DiagnosticData>> GetPushDiagnosticsAsync(Workspace workspace, ProjectId? projectId, DocumentId? documentId, object? id, bool includeSuppressedDiagnostics, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) { return new ValueTask<ImmutableArray<DiagnosticData>>(GetDiagnostics(workspace, projectId, documentId)); } private ImmutableArray<DiagnosticData> GetDiagnostics(Workspace workspace, ProjectId? projectId, DocumentId? documentId) { Assert.Equal(projectId, GetProjectId(workspace)); Assert.Equal(documentId, GetDocumentId(workspace)); return _diagnostic == null ? ImmutableArray<DiagnosticData>.Empty : ImmutableArray.Create(_diagnostic); } public ImmutableArray<DiagnosticBucket> GetPullDiagnosticBuckets(Workspace workspace, ProjectId? projectId, DocumentId? documentId, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) { return GetDiagnosticBuckets(workspace, projectId, documentId); } public ImmutableArray<DiagnosticBucket> GetPushDiagnosticBuckets(Workspace workspace, ProjectId? projectId, DocumentId? documentId, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) { return GetDiagnosticBuckets(workspace, projectId, documentId); } private ImmutableArray<DiagnosticBucket> GetDiagnosticBuckets(Workspace workspace, ProjectId? projectId, DocumentId? documentId) { Assert.Equal(projectId, GetProjectId(workspace)); Assert.Equal(documentId, GetDocumentId(workspace)); return _diagnostic == null ? ImmutableArray<DiagnosticBucket>.Empty : ImmutableArray.Create(new DiagnosticBucket(this, workspace, GetProjectId(workspace), GetDocumentId(workspace))); } internal void CreateDiagnosticAndFireEvents(Workspace workspace, Location location) { var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); _diagnostic = DiagnosticData.Create(Diagnostic.Create(DiagnosticId, "MockCategory", "MockMessage", DiagnosticSeverity.Error, DiagnosticSeverity.Error, isEnabledByDefault: true, warningLevel: 0, location: location), document); DiagnosticsUpdated?.Invoke(this, DiagnosticsUpdatedArgs.DiagnosticsCreated( this, workspace, workspace.CurrentSolution, GetProjectId(workspace), GetDocumentId(workspace), ImmutableArray.Create(_diagnostic))); } private static DocumentId GetDocumentId(Workspace workspace) => workspace.CurrentSolution.Projects.Single().Documents.Single().Id; private static ProjectId GetProjectId(Workspace workspace) => workspace.CurrentSolution.Projects.Single().Id; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { [Export(typeof(IDiagnosticService))] [Shared] [PartNotDiscoverable] internal class MockDiagnosticService : IDiagnosticService { public const string DiagnosticId = "MockId"; private DiagnosticData? _diagnostic; public event EventHandler<DiagnosticsUpdatedArgs>? DiagnosticsUpdated; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MockDiagnosticService() { } [Obsolete] public ImmutableArray<DiagnosticData> GetDiagnostics(Workspace workspace, ProjectId? projectId, DocumentId? documentId, object? id, bool includeSuppressedDiagnostics, CancellationToken cancellationToken) => GetPushDiagnosticsAsync(workspace, projectId, documentId, id, includeSuppressedDiagnostics, InternalDiagnosticsOptions.NormalDiagnosticMode, cancellationToken).AsTask().WaitAndGetResult_CanCallOnBackground(cancellationToken); public ValueTask<ImmutableArray<DiagnosticData>> GetPullDiagnosticsAsync(Workspace workspace, ProjectId? projectId, DocumentId? documentId, object? id, bool includeSuppressedDiagnostics, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) { return new ValueTask<ImmutableArray<DiagnosticData>>(GetDiagnostics(workspace, projectId, documentId)); } public ValueTask<ImmutableArray<DiagnosticData>> GetPushDiagnosticsAsync(Workspace workspace, ProjectId? projectId, DocumentId? documentId, object? id, bool includeSuppressedDiagnostics, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) { return new ValueTask<ImmutableArray<DiagnosticData>>(GetDiagnostics(workspace, projectId, documentId)); } private ImmutableArray<DiagnosticData> GetDiagnostics(Workspace workspace, ProjectId? projectId, DocumentId? documentId) { Assert.Equal(projectId, GetProjectId(workspace)); Assert.Equal(documentId, GetDocumentId(workspace)); return _diagnostic == null ? ImmutableArray<DiagnosticData>.Empty : ImmutableArray.Create(_diagnostic); } public ImmutableArray<DiagnosticBucket> GetPullDiagnosticBuckets(Workspace workspace, ProjectId? projectId, DocumentId? documentId, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) { return GetDiagnosticBuckets(workspace, projectId, documentId); } public ImmutableArray<DiagnosticBucket> GetPushDiagnosticBuckets(Workspace workspace, ProjectId? projectId, DocumentId? documentId, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) { return GetDiagnosticBuckets(workspace, projectId, documentId); } private ImmutableArray<DiagnosticBucket> GetDiagnosticBuckets(Workspace workspace, ProjectId? projectId, DocumentId? documentId) { Assert.Equal(projectId, GetProjectId(workspace)); Assert.Equal(documentId, GetDocumentId(workspace)); return _diagnostic == null ? ImmutableArray<DiagnosticBucket>.Empty : ImmutableArray.Create(new DiagnosticBucket(this, workspace, GetProjectId(workspace), GetDocumentId(workspace))); } internal void CreateDiagnosticAndFireEvents(Workspace workspace, Location location) { var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); _diagnostic = DiagnosticData.Create(Diagnostic.Create(DiagnosticId, "MockCategory", "MockMessage", DiagnosticSeverity.Error, DiagnosticSeverity.Error, isEnabledByDefault: true, warningLevel: 0, location: location), document); DiagnosticsUpdated?.Invoke(this, DiagnosticsUpdatedArgs.DiagnosticsCreated( this, workspace, workspace.CurrentSolution, GetProjectId(workspace), GetDocumentId(workspace), ImmutableArray.Create(_diagnostic))); } private static DocumentId GetDocumentId(Workspace workspace) => workspace.CurrentSolution.Projects.Single().Documents.Single().Id; private static ProjectId GetProjectId(Workspace workspace) => workspace.CurrentSolution.Projects.Single().Id; } }
-1
dotnet/roslyn
55,058
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main
Contributes to https://github.com/dotnet/aspnetcore/issues/33402
tmat
2021-07-22T21:33:59Z
2021-07-23T17:59:16Z
a8d8606f812c649276f0acb5e7ae6afa2a906764
8a986455026077d179eefcc2f5789eb76e7d1453
Port Allow WatchHotReloadService to specify runtime apply-update capabilities (#54012) to main. Contributes to https://github.com/dotnet/aspnetcore/issues/33402
./src/Compilers/CSharp/Portable/Symbols/NamespaceOrTypeSymbol.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.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents either a namespace or a type. /// </summary> internal abstract class NamespaceOrTypeSymbol : Symbol, INamespaceOrTypeSymbolInternal { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Only the compiler can create new instances. internal NamespaceOrTypeSymbol() { } /// <summary> /// Returns true if this symbol is a namespace. If it is not a namespace, it must be a type. /// </summary> public bool IsNamespace { get { return Kind == SymbolKind.Namespace; } } /// <summary> /// Returns true if this symbols is a type. Equivalent to !IsNamespace. /// </summary> public bool IsType { get { return !IsNamespace; } } /// <summary> /// Returns true if this symbol is "virtual", has an implementation, and does not override a /// base class member; i.e., declared with the "virtual" modifier. Does not return true for /// members declared as abstract or override. /// </summary> /// <returns> /// Always returns false. /// </returns> public sealed override bool IsVirtual { get { return false; } } /// <summary> /// Returns true if this symbol was declared to override a base class member; i.e., declared /// with the "override" modifier. Still returns true if member was declared to override /// something, but (erroneously) no member to override exists. /// </summary> /// <returns> /// Always returns false. /// </returns> public sealed override bool IsOverride { get { return false; } } /// <summary> /// Returns true if this symbol has external implementation; i.e., declared with the /// "extern" modifier. /// </summary> /// <returns> /// Always returns false. /// </returns> public sealed override bool IsExtern { get { return false; } } /// <summary> /// Get all the members of this symbol. /// </summary> /// <returns>An ImmutableArray containing all the members of this symbol. If this symbol has no members, /// returns an empty ImmutableArray. Never returns null.</returns> public abstract ImmutableArray<Symbol> GetMembers(); /// <summary> /// Get all the members of this symbol. The members may not be in a particular order, and the order /// may not be stable from call-to-call. /// </summary> /// <returns>An ImmutableArray containing all the members of this symbol. If this symbol has no members, /// returns an empty ImmutableArray. Never returns null.</returns> internal virtual ImmutableArray<Symbol> GetMembersUnordered() { // Default implementation is to use ordered version. When performance indicates, we specialize to have // separate implementation. return GetMembers().ConditionallyDeOrder(); } /// <summary> /// Get all the members of this symbol that have a particular name. /// </summary> /// <returns>An ImmutableArray containing all the members of this symbol with the given name. If there are /// no members with this name, returns an empty ImmutableArray. Never returns null.</returns> public abstract ImmutableArray<Symbol> GetMembers(string name); /// <summary> /// Get all the members of this symbol that are types. The members may not be in a particular order, and the order /// may not be stable from call-to-call. /// </summary> /// <returns>An ImmutableArray containing all the types that are members of this symbol. If this symbol has no type members, /// returns an empty ImmutableArray. Never returns null.</returns> internal virtual ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered() { // Default implementation is to use ordered version. When performance indicates, we specialize to have // separate implementation. return GetTypeMembers().ConditionallyDeOrder(); } /// <summary> /// Get all the members of this symbol that are types. /// </summary> /// <returns>An ImmutableArray containing all the types that are members of this symbol. If this symbol has no type members, /// returns an empty ImmutableArray. Never returns null.</returns> public abstract ImmutableArray<NamedTypeSymbol> GetTypeMembers(); /// <summary> /// Get all the members of this symbol that are types that have a particular name, of any arity. /// </summary> /// <returns>An ImmutableArray containing all the types that are members of this symbol with the given name. /// If this symbol has no type members with this name, /// returns an empty ImmutableArray. Never returns null.</returns> public abstract ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name); /// <summary> /// Get all the members of this symbol that are types that have a particular name and arity /// </summary> /// <returns>An IEnumerable containing all the types that are members of this symbol with the given name and arity. /// If this symbol has no type members with this name and arity, /// returns an empty IEnumerable. Never returns null.</returns> public virtual ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { // default implementation does a post-filter. We can override this if its a performance burden, but // experience is that it won't be. return GetTypeMembers(name).WhereAsArray((t, arity) => t.Arity == arity, arity); } /// <summary> /// Get a source type symbol for the given declaration syntax. /// </summary> /// <returns>Null if there is no matching declaration.</returns> internal SourceNamedTypeSymbol? GetSourceTypeMember(TypeDeclarationSyntax syntax) { return GetSourceTypeMember(syntax.Identifier.ValueText, syntax.Arity, syntax.Kind(), syntax); } /// <summary> /// Get a source type symbol for the given declaration syntax. /// </summary> /// <returns>Null if there is no matching declaration.</returns> internal SourceNamedTypeSymbol? GetSourceTypeMember(DelegateDeclarationSyntax syntax) { return GetSourceTypeMember(syntax.Identifier.ValueText, syntax.Arity, syntax.Kind(), syntax); } /// <summary> /// Get a source type symbol of given name, arity and kind. If a tree and syntax are provided, restrict the results /// to those that are declared within the given syntax. /// </summary> /// <returns>Null if there is no matching declaration.</returns> internal SourceNamedTypeSymbol? GetSourceTypeMember( string name, int arity, SyntaxKind kind, CSharpSyntaxNode syntax) { TypeKind typeKind = kind.ToDeclarationKind().ToTypeKind(); foreach (var member in GetTypeMembers(name, arity)) { var memberT = member as SourceNamedTypeSymbol; if ((object?)memberT != null && memberT.TypeKind == typeKind) { if (syntax != null) { foreach (var loc in memberT.Locations) { if (loc.IsInSource && loc.SourceTree == syntax.SyntaxTree && syntax.Span.Contains(loc.SourceSpan)) { return memberT; } } } else { return memberT; } } } // None found. return null; } /// <summary> /// Lookup an immediately nested type referenced from metadata, names should be /// compared case-sensitively. /// </summary> /// <param name="emittedTypeName"> /// Simple type name, possibly with generic name mangling. /// </param> /// <returns> /// Symbol for the type, or MissingMetadataSymbol if the type isn't found. /// </returns> internal virtual NamedTypeSymbol LookupMetadataType(ref MetadataTypeName emittedTypeName) { Debug.Assert(!emittedTypeName.IsNull); NamespaceOrTypeSymbol scope = this; if (scope.Kind == SymbolKind.ErrorType) { return new MissingMetadataTypeSymbol.Nested((NamedTypeSymbol)scope, ref emittedTypeName); } NamedTypeSymbol? namedType = null; ImmutableArray<NamedTypeSymbol> namespaceOrTypeMembers; bool isTopLevel = scope.IsNamespace; Debug.Assert(!isTopLevel || scope.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat) == emittedTypeName.NamespaceName); if (emittedTypeName.IsMangled) { Debug.Assert(!emittedTypeName.UnmangledTypeName.Equals(emittedTypeName.TypeName) && emittedTypeName.InferredArity > 0); if (emittedTypeName.ForcedArity == -1 || emittedTypeName.ForcedArity == emittedTypeName.InferredArity) { // Let's handle mangling case first. namespaceOrTypeMembers = scope.GetTypeMembers(emittedTypeName.UnmangledTypeName); foreach (var named in namespaceOrTypeMembers) { if (emittedTypeName.InferredArity == named.Arity && named.MangleName) { if ((object?)namedType != null) { namedType = null; break; } namedType = named; } } } } else { Debug.Assert(ReferenceEquals(emittedTypeName.UnmangledTypeName, emittedTypeName.TypeName) && emittedTypeName.InferredArity == 0); } // Now try lookup without removing generic arity mangling. int forcedArity = emittedTypeName.ForcedArity; if (emittedTypeName.UseCLSCompliantNameArityEncoding) { // Only types with arity 0 are acceptable, we already examined types with mangled names. if (emittedTypeName.InferredArity > 0) { goto Done; } else if (forcedArity == -1) { forcedArity = 0; } else if (forcedArity != 0) { goto Done; } else { Debug.Assert(forcedArity == emittedTypeName.InferredArity); } } namespaceOrTypeMembers = scope.GetTypeMembers(emittedTypeName.TypeName); foreach (var named in namespaceOrTypeMembers) { if (!named.MangleName && (forcedArity == -1 || forcedArity == named.Arity)) { if ((object?)namedType != null) { namedType = null; break; } namedType = named; } } Done: if ((object?)namedType == null) { if (isTopLevel) { return new MissingMetadataTypeSymbol.TopLevel(scope.ContainingModule, ref emittedTypeName); } else { return new MissingMetadataTypeSymbol.Nested((NamedTypeSymbol)scope, ref emittedTypeName); } } return namedType; } /// <summary> /// Finds types or namespaces described by a qualified name. /// </summary> /// <param name="qualifiedName">Sequence of simple plain names.</param> /// <returns> /// A set of namespace or type symbols with given qualified name (might comprise of types with multiple generic arities), /// or an empty set if the member can't be found (the qualified name is ambiguous or the symbol doesn't exist). /// </returns> /// <remarks> /// "C.D" matches C.D, C{T}.D, C{S,T}.D{U}, etc. /// </remarks> internal IEnumerable<NamespaceOrTypeSymbol>? GetNamespaceOrTypeByQualifiedName(IEnumerable<string> qualifiedName) { NamespaceOrTypeSymbol namespaceOrType = this; IEnumerable<NamespaceOrTypeSymbol>? symbols = null; foreach (string name in qualifiedName) { if (symbols != null) { // there might be multiple types of different arity, prefer a non-generic type: namespaceOrType = symbols.OfMinimalArity(); if ((object)namespaceOrType == null) { return SpecializedCollections.EmptyEnumerable<NamespaceOrTypeSymbol>(); } } symbols = namespaceOrType.GetMembers(name).OfType<NamespaceOrTypeSymbol>(); } return symbols; } } }
// Licensed to the .NET Foundation under one or more 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.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents either a namespace or a type. /// </summary> internal abstract class NamespaceOrTypeSymbol : Symbol, INamespaceOrTypeSymbolInternal { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Only the compiler can create new instances. internal NamespaceOrTypeSymbol() { } /// <summary> /// Returns true if this symbol is a namespace. If it is not a namespace, it must be a type. /// </summary> public bool IsNamespace { get { return Kind == SymbolKind.Namespace; } } /// <summary> /// Returns true if this symbols is a type. Equivalent to !IsNamespace. /// </summary> public bool IsType { get { return !IsNamespace; } } /// <summary> /// Returns true if this symbol is "virtual", has an implementation, and does not override a /// base class member; i.e., declared with the "virtual" modifier. Does not return true for /// members declared as abstract or override. /// </summary> /// <returns> /// Always returns false. /// </returns> public sealed override bool IsVirtual { get { return false; } } /// <summary> /// Returns true if this symbol was declared to override a base class member; i.e., declared /// with the "override" modifier. Still returns true if member was declared to override /// something, but (erroneously) no member to override exists. /// </summary> /// <returns> /// Always returns false. /// </returns> public sealed override bool IsOverride { get { return false; } } /// <summary> /// Returns true if this symbol has external implementation; i.e., declared with the /// "extern" modifier. /// </summary> /// <returns> /// Always returns false. /// </returns> public sealed override bool IsExtern { get { return false; } } /// <summary> /// Get all the members of this symbol. /// </summary> /// <returns>An ImmutableArray containing all the members of this symbol. If this symbol has no members, /// returns an empty ImmutableArray. Never returns null.</returns> public abstract ImmutableArray<Symbol> GetMembers(); /// <summary> /// Get all the members of this symbol. The members may not be in a particular order, and the order /// may not be stable from call-to-call. /// </summary> /// <returns>An ImmutableArray containing all the members of this symbol. If this symbol has no members, /// returns an empty ImmutableArray. Never returns null.</returns> internal virtual ImmutableArray<Symbol> GetMembersUnordered() { // Default implementation is to use ordered version. When performance indicates, we specialize to have // separate implementation. return GetMembers().ConditionallyDeOrder(); } /// <summary> /// Get all the members of this symbol that have a particular name. /// </summary> /// <returns>An ImmutableArray containing all the members of this symbol with the given name. If there are /// no members with this name, returns an empty ImmutableArray. Never returns null.</returns> public abstract ImmutableArray<Symbol> GetMembers(string name); /// <summary> /// Get all the members of this symbol that are types. The members may not be in a particular order, and the order /// may not be stable from call-to-call. /// </summary> /// <returns>An ImmutableArray containing all the types that are members of this symbol. If this symbol has no type members, /// returns an empty ImmutableArray. Never returns null.</returns> internal virtual ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered() { // Default implementation is to use ordered version. When performance indicates, we specialize to have // separate implementation. return GetTypeMembers().ConditionallyDeOrder(); } /// <summary> /// Get all the members of this symbol that are types. /// </summary> /// <returns>An ImmutableArray containing all the types that are members of this symbol. If this symbol has no type members, /// returns an empty ImmutableArray. Never returns null.</returns> public abstract ImmutableArray<NamedTypeSymbol> GetTypeMembers(); /// <summary> /// Get all the members of this symbol that are types that have a particular name, of any arity. /// </summary> /// <returns>An ImmutableArray containing all the types that are members of this symbol with the given name. /// If this symbol has no type members with this name, /// returns an empty ImmutableArray. Never returns null.</returns> public abstract ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name); /// <summary> /// Get all the members of this symbol that are types that have a particular name and arity /// </summary> /// <returns>An IEnumerable containing all the types that are members of this symbol with the given name and arity. /// If this symbol has no type members with this name and arity, /// returns an empty IEnumerable. Never returns null.</returns> public virtual ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { // default implementation does a post-filter. We can override this if its a performance burden, but // experience is that it won't be. return GetTypeMembers(name).WhereAsArray((t, arity) => t.Arity == arity, arity); } /// <summary> /// Get a source type symbol for the given declaration syntax. /// </summary> /// <returns>Null if there is no matching declaration.</returns> internal SourceNamedTypeSymbol? GetSourceTypeMember(TypeDeclarationSyntax syntax) { return GetSourceTypeMember(syntax.Identifier.ValueText, syntax.Arity, syntax.Kind(), syntax); } /// <summary> /// Get a source type symbol for the given declaration syntax. /// </summary> /// <returns>Null if there is no matching declaration.</returns> internal SourceNamedTypeSymbol? GetSourceTypeMember(DelegateDeclarationSyntax syntax) { return GetSourceTypeMember(syntax.Identifier.ValueText, syntax.Arity, syntax.Kind(), syntax); } /// <summary> /// Get a source type symbol of given name, arity and kind. If a tree and syntax are provided, restrict the results /// to those that are declared within the given syntax. /// </summary> /// <returns>Null if there is no matching declaration.</returns> internal SourceNamedTypeSymbol? GetSourceTypeMember( string name, int arity, SyntaxKind kind, CSharpSyntaxNode syntax) { TypeKind typeKind = kind.ToDeclarationKind().ToTypeKind(); foreach (var member in GetTypeMembers(name, arity)) { var memberT = member as SourceNamedTypeSymbol; if ((object?)memberT != null && memberT.TypeKind == typeKind) { if (syntax != null) { foreach (var loc in memberT.Locations) { if (loc.IsInSource && loc.SourceTree == syntax.SyntaxTree && syntax.Span.Contains(loc.SourceSpan)) { return memberT; } } } else { return memberT; } } } // None found. return null; } /// <summary> /// Lookup an immediately nested type referenced from metadata, names should be /// compared case-sensitively. /// </summary> /// <param name="emittedTypeName"> /// Simple type name, possibly with generic name mangling. /// </param> /// <returns> /// Symbol for the type, or MissingMetadataSymbol if the type isn't found. /// </returns> internal virtual NamedTypeSymbol LookupMetadataType(ref MetadataTypeName emittedTypeName) { Debug.Assert(!emittedTypeName.IsNull); NamespaceOrTypeSymbol scope = this; if (scope.Kind == SymbolKind.ErrorType) { return new MissingMetadataTypeSymbol.Nested((NamedTypeSymbol)scope, ref emittedTypeName); } NamedTypeSymbol? namedType = null; ImmutableArray<NamedTypeSymbol> namespaceOrTypeMembers; bool isTopLevel = scope.IsNamespace; Debug.Assert(!isTopLevel || scope.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat) == emittedTypeName.NamespaceName); if (emittedTypeName.IsMangled) { Debug.Assert(!emittedTypeName.UnmangledTypeName.Equals(emittedTypeName.TypeName) && emittedTypeName.InferredArity > 0); if (emittedTypeName.ForcedArity == -1 || emittedTypeName.ForcedArity == emittedTypeName.InferredArity) { // Let's handle mangling case first. namespaceOrTypeMembers = scope.GetTypeMembers(emittedTypeName.UnmangledTypeName); foreach (var named in namespaceOrTypeMembers) { if (emittedTypeName.InferredArity == named.Arity && named.MangleName) { if ((object?)namedType != null) { namedType = null; break; } namedType = named; } } } } else { Debug.Assert(ReferenceEquals(emittedTypeName.UnmangledTypeName, emittedTypeName.TypeName) && emittedTypeName.InferredArity == 0); } // Now try lookup without removing generic arity mangling. int forcedArity = emittedTypeName.ForcedArity; if (emittedTypeName.UseCLSCompliantNameArityEncoding) { // Only types with arity 0 are acceptable, we already examined types with mangled names. if (emittedTypeName.InferredArity > 0) { goto Done; } else if (forcedArity == -1) { forcedArity = 0; } else if (forcedArity != 0) { goto Done; } else { Debug.Assert(forcedArity == emittedTypeName.InferredArity); } } namespaceOrTypeMembers = scope.GetTypeMembers(emittedTypeName.TypeName); foreach (var named in namespaceOrTypeMembers) { if (!named.MangleName && (forcedArity == -1 || forcedArity == named.Arity)) { if ((object?)namedType != null) { namedType = null; break; } namedType = named; } } Done: if ((object?)namedType == null) { if (isTopLevel) { return new MissingMetadataTypeSymbol.TopLevel(scope.ContainingModule, ref emittedTypeName); } else { return new MissingMetadataTypeSymbol.Nested((NamedTypeSymbol)scope, ref emittedTypeName); } } return namedType; } /// <summary> /// Finds types or namespaces described by a qualified name. /// </summary> /// <param name="qualifiedName">Sequence of simple plain names.</param> /// <returns> /// A set of namespace or type symbols with given qualified name (might comprise of types with multiple generic arities), /// or an empty set if the member can't be found (the qualified name is ambiguous or the symbol doesn't exist). /// </returns> /// <remarks> /// "C.D" matches C.D, C{T}.D, C{S,T}.D{U}, etc. /// </remarks> internal IEnumerable<NamespaceOrTypeSymbol>? GetNamespaceOrTypeByQualifiedName(IEnumerable<string> qualifiedName) { NamespaceOrTypeSymbol namespaceOrType = this; IEnumerable<NamespaceOrTypeSymbol>? symbols = null; foreach (string name in qualifiedName) { if (symbols != null) { // there might be multiple types of different arity, prefer a non-generic type: namespaceOrType = symbols.OfMinimalArity(); if ((object)namespaceOrType == null) { return SpecializedCollections.EmptyEnumerable<NamespaceOrTypeSymbol>(); } } symbols = namespaceOrType.GetMembers(name).OfType<NamespaceOrTypeSymbol>(); } return symbols; } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/EditorFeatures/Core/Implementation/EditAndContinue/EditAndContinueDiagnosticAnalyzer.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.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal sealed class EditAndContinueDiagnosticAnalyzer : DocumentDiagnosticAnalyzer, IBuiltInAnalyzer { private static readonly ImmutableArray<DiagnosticDescriptor> s_supportedDiagnostics = EditAndContinueDiagnosticDescriptors.GetDescriptors(); // Return known descriptors. This will not include module diagnostics reported on behalf of the debugger. public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => s_supportedDiagnostics; public DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; public bool OpenFileOnly(OptionSet options) => false; // No syntax diagnostics produced by the EnC engine. public override Task<ImmutableArray<Diagnostic>> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) => SpecializedTasks.EmptyImmutableArray<Diagnostic>(); public override Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken) { var workspace = document.Project.Solution.Workspace; // do not load EnC service and its dependencies if the app is not running: var debuggingService = workspace.Services.GetRequiredService<IDebuggingWorkspaceService>(); if (debuggingService.CurrentDebuggingState == DebuggingState.Design) { return SpecializedTasks.EmptyImmutableArray<Diagnostic>(); } return AnalyzeSemanticsImplAsync(workspace, document, cancellationToken); } // Copied from // https://github.com/dotnet/sdk/blob/main/src/RazorSdk/SourceGenerators/RazorSourceGenerator.Helpers.cs#L32 private static string GetIdentifierFromPath(string filePath) { var builder = new StringBuilder(filePath.Length); for (var i = 0; i < filePath.Length; i++) { switch (filePath[i]) { case ':' or '\\' or '/': case char ch when !char.IsLetterOrDigit(ch): builder.Append('_'); break; default: builder.Append(filePath[i]); break; } } return builder.ToString(); } [MethodImpl(MethodImplOptions.NoInlining)] private static async Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsImplAsync(Workspace workspace, Document designTimeDocument, CancellationToken cancellationToken) { var designTimeSolution = designTimeDocument.Project.Solution; var compileTimeSolution = workspace.Services.GetRequiredService<ICompileTimeSolutionProvider>().GetCompileTimeSolution(designTimeSolution); var compileTimeDocument = await compileTimeSolution.GetDocumentAsync(designTimeDocument.Id, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (compileTimeDocument == null) { if (!designTimeDocument.State.Attributes.DesignTimeOnly || !designTimeDocument.FilePath.EndsWith(".razor.g.cs")) { return ImmutableArray<Diagnostic>.Empty; } var relativeDocumentPath = Path.Combine("\\", PathUtilities.GetRelativePath(PathUtilities.GetDirectoryName(designTimeDocument.Project.FilePath), designTimeDocument.FilePath)[..^".g.cs".Length]); var generatedDocumentPath = Path.Combine("Microsoft.NET.Sdk.Razor.SourceGenerators", "Microsoft.NET.Sdk.Razor.SourceGenerators.RazorSourceGenerator", GetIdentifierFromPath(relativeDocumentPath)) + ".cs"; var sourceGeneratedDocuments = await compileTimeSolution.GetRequiredProject(designTimeDocument.Project.Id).GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false); compileTimeDocument = sourceGeneratedDocuments.SingleOrDefault(d => d.FilePath == generatedDocumentPath); if (compileTimeDocument == null) { return ImmutableArray<Diagnostic>.Empty; } } // EnC services should never be called on a design-time solution. var proxy = new RemoteEditAndContinueServiceProxy(workspace); var activeStatementSpanProvider = new ActiveStatementSpanProvider(async (documentId, filePath, cancellationToken) => { var trackingService = workspace.Services.GetRequiredService<IActiveStatementTrackingService>(); return await trackingService.GetSpansAsync(compileTimeSolution, documentId, filePath, cancellationToken).ConfigureAwait(false); }); return await proxy.GetDocumentDiagnosticsAsync(compileTimeDocument, designTimeDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal sealed class EditAndContinueDiagnosticAnalyzer : DocumentDiagnosticAnalyzer, IBuiltInAnalyzer { private static readonly ImmutableArray<DiagnosticDescriptor> s_supportedDiagnostics = EditAndContinueDiagnosticDescriptors.GetDescriptors(); // Return known descriptors. This will not include module diagnostics reported on behalf of the debugger. public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => s_supportedDiagnostics; public DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; public bool OpenFileOnly(OptionSet options) => false; // No syntax diagnostics produced by the EnC engine. public override Task<ImmutableArray<Diagnostic>> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) => SpecializedTasks.EmptyImmutableArray<Diagnostic>(); public override Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken) { var workspace = document.Project.Solution.Workspace; // do not load EnC service and its dependencies if the app is not running: var debuggingService = workspace.Services.GetRequiredService<IDebuggingWorkspaceService>(); if (debuggingService.CurrentDebuggingState == DebuggingState.Design) { return SpecializedTasks.EmptyImmutableArray<Diagnostic>(); } return AnalyzeSemanticsImplAsync(workspace, document, cancellationToken); } [MethodImpl(MethodImplOptions.NoInlining)] private static async Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsImplAsync(Workspace workspace, Document designTimeDocument, CancellationToken cancellationToken) { var designTimeSolution = designTimeDocument.Project.Solution; var compileTimeSolution = workspace.Services.GetRequiredService<ICompileTimeSolutionProvider>().GetCompileTimeSolution(designTimeSolution); var compileTimeDocument = await CompileTimeSolutionProvider.TryGetCompileTimeDocumentAsync(designTimeDocument, compileTimeSolution, cancellationToken).ConfigureAwait(false); if (compileTimeDocument == null) { return ImmutableArray<Diagnostic>.Empty; } // EnC services should never be called on a design-time solution. var proxy = new RemoteEditAndContinueServiceProxy(workspace); var activeStatementSpanProvider = new ActiveStatementSpanProvider(async (documentId, filePath, cancellationToken) => { var trackingService = workspace.Services.GetRequiredService<IActiveStatementTrackingService>(); return await trackingService.GetSpansAsync(compileTimeSolution, documentId, filePath, cancellationToken).ConfigureAwait(false); }); return await proxy.GetDocumentDiagnosticsAsync(compileTimeDocument, designTimeDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); } } }
1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/EditorFeatures/Test/EditAndContinue/RemoteEditAndContinueServiceTests.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 System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Roslyn.VisualStudio.Next.UnitTests.EditAndContinue { [UseExportProvider] public class RemoteEditAndContinueServiceTests { [ExportWorkspaceServiceFactory(typeof(IEditAndContinueWorkspaceService), ServiceLayer.Test), Shared] internal sealed class MockEncServiceFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MockEncServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new MockEditAndContinueWorkspaceService(); } [Theory, CombinatorialData] public async Task Proxy(TestHost testHost) { var localComposition = EditorTestCompositions.EditorFeatures.WithTestHostParts(testHost); if (testHost == TestHost.InProcess) { localComposition = localComposition.AddParts(typeof(MockEncServiceFactory)); } using var localWorkspace = new TestWorkspace(composition: localComposition); MockEditAndContinueWorkspaceService mockEncService; var clientProvider = (InProcRemoteHostClientProvider?)localWorkspace.Services.GetService<IRemoteHostClientProvider>(); if (testHost == TestHost.InProcess) { Assert.Null(clientProvider); mockEncService = (MockEditAndContinueWorkspaceService)localWorkspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); } else { Assert.NotNull(clientProvider); clientProvider!.AdditionalRemoteParts = new[] { typeof(MockEncServiceFactory) }; var client = await InProcRemoteHostClient.GetTestClientAsync(localWorkspace).ConfigureAwait(false); var remoteWorkspace = client.TestData.WorkspaceManager.GetWorkspace(); mockEncService = (MockEditAndContinueWorkspaceService)remoteWorkspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); } localWorkspace.ChangeSolution(localWorkspace.CurrentSolution. AddProject("proj", "proj", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From("class C { }", Encoding.UTF8), filePath: "test.cs").Project.Solution); var solution = localWorkspace.CurrentSolution; var project = solution.Projects.Single(); var document = project.Documents.Single(); var mockDiagnosticService = new MockDiagnosticAnalyzerService(); void VerifyReanalyzeInvocation(ImmutableArray<DocumentId> documentIds) { AssertEx.Equal(documentIds, mockDiagnosticService.DocumentsToReanalyze); mockDiagnosticService.DocumentsToReanalyze.Clear(); } var diagnosticUpdateSource = new EditAndContinueDiagnosticUpdateSource(); var emitDiagnosticsUpdated = new List<DiagnosticsUpdatedArgs>(); var emitDiagnosticsClearedCount = 0; diagnosticUpdateSource.DiagnosticsUpdated += (object sender, DiagnosticsUpdatedArgs args) => emitDiagnosticsUpdated.Add(args); diagnosticUpdateSource.DiagnosticsCleared += (object sender, EventArgs args) => emitDiagnosticsClearedCount++; var span1 = new LinePositionSpan(new LinePosition(1, 2), new LinePosition(1, 5)); var moduleId1 = new Guid("{44444444-1111-1111-1111-111111111111}"); var methodId1 = new ManagedMethodId(moduleId1, token: 0x06000003, version: 2); var instructionId1 = new ManagedInstructionId(methodId1, ilOffset: 10); var as1 = new ManagedActiveStatementDebugInfo( instructionId1, documentName: "test.cs", span1.ToSourceSpan(), flags: ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.PartiallyExecuted); var methodId2 = new ManagedModuleMethodId(token: 0x06000002, version: 1); var exceptionRegionUpdate1 = new ManagedExceptionRegionUpdate( methodId2, delta: 1, newSpan: new SourceSpan(1, 2, 1, 5)); var document1 = localWorkspace.CurrentSolution.Projects.Single().Documents.Single(); var activeSpans1 = ImmutableArray.Create( new ActiveStatementSpan(0, new LinePositionSpan(new LinePosition(1, 2), new LinePosition(3, 4)), ActiveStatementFlags.IsNonLeafFrame, document.Id)); var activeStatementSpanProvider = new ActiveStatementSpanProvider((documentId, path, cancellationToken) => { Assert.Equal(document1.Id, documentId); Assert.Equal("test.cs", path); return new(activeSpans1); }); var proxy = new RemoteEditAndContinueServiceProxy(localWorkspace); // StartDebuggingSession IManagedEditAndContinueDebuggerService? remoteDebuggeeModuleMetadataProvider = null; var debuggingSession = mockEncService.StartDebuggingSessionImpl = (solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics) => { Assert.Equal("proj", solution.Projects.Single().Name); AssertEx.Equal(new[] { document1.Id }, captureMatchingDocuments); Assert.False(captureAllMatchingDocuments); Assert.True(reportDiagnostics); remoteDebuggeeModuleMetadataProvider = debuggerService; return new DebuggingSessionId(1); }; var sessionProxy = await proxy.StartDebuggingSessionAsync( localWorkspace.CurrentSolution, debuggerService: new MockManagedEditAndContinueDebuggerService() { IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForModule, "can't do enc"), GetActiveStatementsImpl = () => ImmutableArray.Create(as1) }, captureMatchingDocuments: ImmutableArray.Create(document1.Id), captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None).ConfigureAwait(false); Contract.ThrowIfNull(sessionProxy); // BreakStateEntered mockEncService.BreakStateEnteredImpl = (out ImmutableArray<DocumentId> documentsToReanalyze) => { documentsToReanalyze = ImmutableArray.Create(document.Id); }; await sessionProxy.BreakStateEnteredAsync(mockDiagnosticService, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id)); var activeStatement = (await remoteDebuggeeModuleMetadataProvider!.GetActiveStatementsAsync(CancellationToken.None).ConfigureAwait(false)).Single(); Assert.Equal(as1.ActiveInstruction, activeStatement.ActiveInstruction); Assert.Equal(as1.SourceSpan, activeStatement.SourceSpan); Assert.Equal(as1.Flags, activeStatement.Flags); var availability = await remoteDebuggeeModuleMetadataProvider!.GetAvailabilityAsync(moduleId1, CancellationToken.None).ConfigureAwait(false); Assert.Equal(new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForModule, "can't do enc"), availability); // HasChanges mockEncService.HasChangesImpl = (solution, activeStatementSpanProvider, sourceFilePath) => { Assert.Equal("proj", solution.Projects.Single().Name); Assert.Equal("test.cs", sourceFilePath); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result); return true; }; Assert.True(await sessionProxy.HasChangesAsync(localWorkspace.CurrentSolution, activeStatementSpanProvider, "test.cs", CancellationToken.None).ConfigureAwait(false)); // EmitSolutionUpdate var diagnosticDescriptor1 = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); mockEncService.EmitSolutionUpdateImpl = (solution, activeStatementSpanProvider) => { var project = solution.Projects.Single(); Assert.Equal("proj", project.Name); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result); var deltas = ImmutableArray.Create(new ManagedModuleUpdate( module: moduleId1, ilDelta: ImmutableArray.Create<byte>(1, 2), metadataDelta: ImmutableArray.Create<byte>(3, 4), pdbDelta: ImmutableArray.Create<byte>(5, 6), updatedMethods: ImmutableArray.Create(0x06000001), updatedTypes: ImmutableArray.Create(0x02000001), sequencePoints: ImmutableArray.Create(new SequencePointUpdates("file.cs", ImmutableArray.Create(new SourceLineUpdate(1, 2)))), activeStatements: ImmutableArray.Create(new ManagedActiveStatementUpdate(instructionId1.Method.Method, instructionId1.ILOffset, span1.ToSourceSpan())), exceptionRegions: ImmutableArray.Create(exceptionRegionUpdate1))); var syntaxTree = project.Documents.Single().GetSyntaxTreeSynchronously(CancellationToken.None)!; var documentDiagnostic = Diagnostic.Create(diagnosticDescriptor1, Location.Create(syntaxTree, TextSpan.FromBounds(1, 2)), new[] { "doc", "some error" }); var projectDiagnostic = Diagnostic.Create(diagnosticDescriptor1, Location.None, new[] { "proj", "some error" }); var updates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Ready, deltas); var diagnostics = ImmutableArray.Create((project.Id, ImmutableArray.Create(documentDiagnostic, projectDiagnostic))); var documentsWithRudeEdits = ImmutableArray.Create((document1.Id, ImmutableArray<RudeEditDiagnostic>.Empty)); return new(updates, diagnostics, documentsWithRudeEdits); }; var (updates, _, _) = await sessionProxy.EmitSolutionUpdateAsync(localWorkspace.CurrentSolution, activeStatementSpanProvider, mockDiagnosticService, diagnosticUpdateSource, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document1.Id)); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Equal(1, emitDiagnosticsClearedCount); emitDiagnosticsClearedCount = 0; AssertEx.Equal(new[] { $"[{project.Id}] Error ENC1001: test.cs(0, 1, 0, 2): {string.Format(FeaturesResources.ErrorReadingFile, "doc", "some error")}", $"[{project.Id}] Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "proj", "some error")}" }, emitDiagnosticsUpdated.Select(update => { var d = update.GetPushDiagnostics(localWorkspace, InternalDiagnosticsOptions.NormalDiagnosticMode).Single(); return $"[{d.ProjectId}] {d.Severity} {d.Id}:" + (d.DataLocation != null ? $" {d.DataLocation.OriginalFilePath}({d.DataLocation.OriginalStartLine}, {d.DataLocation.OriginalStartColumn}, {d.DataLocation.OriginalEndLine}, {d.DataLocation.OriginalEndColumn}):" : "") + $" {d.Message}"; })); emitDiagnosticsUpdated.Clear(); var delta = updates.Updates.Single(); Assert.Equal(moduleId1, delta.Module); AssertEx.Equal(new byte[] { 1, 2 }, delta.ILDelta); AssertEx.Equal(new byte[] { 3, 4 }, delta.MetadataDelta); AssertEx.Equal(new byte[] { 5, 6 }, delta.PdbDelta); AssertEx.Equal(new[] { 0x06000001 }, delta.UpdatedMethods); AssertEx.Equal(new[] { 0x02000001 }, delta.UpdatedTypes); var lineEdit = delta.SequencePoints.Single(); Assert.Equal("file.cs", lineEdit.FileName); AssertEx.Equal(new[] { new SourceLineUpdate(1, 2) }, lineEdit.LineUpdates); Assert.Equal(exceptionRegionUpdate1, delta.ExceptionRegions.Single()); var activeStatements = delta.ActiveStatements.Single(); Assert.Equal(instructionId1.Method.Method, activeStatements.Method); Assert.Equal(instructionId1.ILOffset, activeStatements.ILOffset); Assert.Equal(span1, activeStatements.NewSpan.ToLinePositionSpan()); // CommitSolutionUpdate mockEncService.CommitSolutionUpdateImpl = (out ImmutableArray<DocumentId> documentsToReanalyze) => { documentsToReanalyze = ImmutableArray.Create(document.Id); }; await sessionProxy.CommitSolutionUpdateAsync(mockDiagnosticService, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id)); // DiscardSolutionUpdate var called = false; mockEncService.DiscardSolutionUpdateImpl = () => called = true; await sessionProxy.DiscardSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); Assert.True(called); // GetCurrentActiveStatementPosition mockEncService.GetCurrentActiveStatementPositionImpl = (solution, activeStatementSpanProvider, instructionId) => { Assert.Equal("proj", solution.Projects.Single().Name); Assert.Equal(instructionId1, instructionId); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result); return new LinePositionSpan(new LinePosition(1, 2), new LinePosition(1, 5)); }; Assert.Equal(span1, await sessionProxy.GetCurrentActiveStatementPositionAsync( localWorkspace.CurrentSolution, activeStatementSpanProvider, instructionId1, CancellationToken.None).ConfigureAwait(false)); // IsActiveStatementInExceptionRegion mockEncService.IsActiveStatementInExceptionRegionImpl = (solution, instructionId) => { Assert.Equal(instructionId1, instructionId); return true; }; Assert.True(await sessionProxy.IsActiveStatementInExceptionRegionAsync(localWorkspace.CurrentSolution, instructionId1, CancellationToken.None).ConfigureAwait(false)); // GetBaseActiveStatementSpans var activeStatementSpan1 = new ActiveStatementSpan(0, span1, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.PartiallyExecuted, unmappedDocumentId: document1.Id); mockEncService.GetBaseActiveStatementSpansImpl = (solution, documentIds) => { AssertEx.Equal(new[] { document1.Id }, documentIds); return ImmutableArray.Create(ImmutableArray.Create(activeStatementSpan1)); }; var baseActiveSpans = await sessionProxy.GetBaseActiveStatementSpansAsync(localWorkspace.CurrentSolution, ImmutableArray.Create(document1.Id), CancellationToken.None).ConfigureAwait(false); Assert.Equal(activeStatementSpan1, baseActiveSpans.Single().Single()); // GetDocumentActiveStatementSpans mockEncService.GetAdjustedActiveStatementSpansImpl = (document, activeStatementSpanProvider) => { Assert.Equal("test.cs", document.Name); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document.Id, "test.cs", CancellationToken.None).AsTask().Result); return ImmutableArray.Create(activeStatementSpan1); }; var documentActiveSpans = await sessionProxy.GetAdjustedActiveStatementSpansAsync(document1, activeStatementSpanProvider, CancellationToken.None).ConfigureAwait(false); Assert.Equal(activeStatementSpan1, documentActiveSpans.Single()); // GetDocumentActiveStatementSpans (default array) mockEncService.GetAdjustedActiveStatementSpansImpl = (document, _) => default; documentActiveSpans = await sessionProxy.GetAdjustedActiveStatementSpansAsync(document1, activeStatementSpanProvider, CancellationToken.None).ConfigureAwait(false); Assert.True(documentActiveSpans.IsDefault); // OnSourceFileUpdatedAsync called = false; mockEncService.OnSourceFileUpdatedImpl = updatedDocument => { Assert.Equal(document.Id, updatedDocument.Id); called = true; }; await proxy.OnSourceFileUpdatedAsync(document, CancellationToken.None).ConfigureAwait(false); Assert.True(called); // EndDebuggingSession mockEncService.EndDebuggingSessionImpl = (out ImmutableArray<DocumentId> documentsToReanalyze) => { documentsToReanalyze = ImmutableArray.Create(document.Id); }; await sessionProxy.EndDebuggingSessionAsync(diagnosticUpdateSource, mockDiagnosticService, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id)); Assert.Equal(1, emitDiagnosticsClearedCount); emitDiagnosticsClearedCount = 0; Assert.Empty(emitDiagnosticsUpdated); } } }
// Licensed to the .NET Foundation under one or more 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 System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Roslyn.VisualStudio.Next.UnitTests.EditAndContinue { [UseExportProvider] public class RemoteEditAndContinueServiceTests { [ExportWorkspaceServiceFactory(typeof(IEditAndContinueWorkspaceService), ServiceLayer.Test), Shared] internal sealed class MockEncServiceFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MockEncServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new MockEditAndContinueWorkspaceService(); } [Theory, CombinatorialData] public async Task Proxy(TestHost testHost) { var localComposition = EditorTestCompositions.EditorFeatures.WithTestHostParts(testHost); if (testHost == TestHost.InProcess) { localComposition = localComposition.AddParts(typeof(MockEncServiceFactory)); } using var localWorkspace = new TestWorkspace(composition: localComposition); MockEditAndContinueWorkspaceService mockEncService; var clientProvider = (InProcRemoteHostClientProvider?)localWorkspace.Services.GetService<IRemoteHostClientProvider>(); if (testHost == TestHost.InProcess) { Assert.Null(clientProvider); mockEncService = (MockEditAndContinueWorkspaceService)localWorkspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); } else { Assert.NotNull(clientProvider); clientProvider!.AdditionalRemoteParts = new[] { typeof(MockEncServiceFactory) }; var client = await InProcRemoteHostClient.GetTestClientAsync(localWorkspace).ConfigureAwait(false); var remoteWorkspace = client.TestData.WorkspaceManager.GetWorkspace(); mockEncService = (MockEditAndContinueWorkspaceService)remoteWorkspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); } localWorkspace.ChangeSolution(localWorkspace.CurrentSolution. AddProject("proj", "proj", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From("class C { }", Encoding.UTF8), filePath: "test.cs").Project.Solution); var solution = localWorkspace.CurrentSolution; var project = solution.Projects.Single(); var document = project.Documents.Single(); var mockDiagnosticService = new MockDiagnosticAnalyzerService(); void VerifyReanalyzeInvocation(ImmutableArray<DocumentId> documentIds) { AssertEx.Equal(documentIds, mockDiagnosticService.DocumentsToReanalyze); mockDiagnosticService.DocumentsToReanalyze.Clear(); } var diagnosticUpdateSource = new EditAndContinueDiagnosticUpdateSource(); var emitDiagnosticsUpdated = new List<DiagnosticsUpdatedArgs>(); var emitDiagnosticsClearedCount = 0; diagnosticUpdateSource.DiagnosticsUpdated += (object sender, DiagnosticsUpdatedArgs args) => emitDiagnosticsUpdated.Add(args); diagnosticUpdateSource.DiagnosticsCleared += (object sender, EventArgs args) => emitDiagnosticsClearedCount++; var span1 = new LinePositionSpan(new LinePosition(1, 2), new LinePosition(1, 5)); var moduleId1 = new Guid("{44444444-1111-1111-1111-111111111111}"); var methodId1 = new ManagedMethodId(moduleId1, token: 0x06000003, version: 2); var instructionId1 = new ManagedInstructionId(methodId1, ilOffset: 10); var as1 = new ManagedActiveStatementDebugInfo( instructionId1, documentName: "test.cs", span1.ToSourceSpan(), flags: ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.PartiallyExecuted); var methodId2 = new ManagedModuleMethodId(token: 0x06000002, version: 1); var exceptionRegionUpdate1 = new ManagedExceptionRegionUpdate( methodId2, delta: 1, newSpan: new SourceSpan(1, 2, 1, 5)); var document1 = localWorkspace.CurrentSolution.Projects.Single().Documents.Single(); var activeSpans1 = ImmutableArray.Create( new ActiveStatementSpan(0, new LinePositionSpan(new LinePosition(1, 2), new LinePosition(3, 4)), ActiveStatementFlags.IsNonLeafFrame, document.Id)); var activeStatementSpanProvider = new ActiveStatementSpanProvider((documentId, path, cancellationToken) => { Assert.Equal(document1.Id, documentId); Assert.Equal("test.cs", path); return new(activeSpans1); }); var proxy = new RemoteEditAndContinueServiceProxy(localWorkspace); // StartDebuggingSession IManagedEditAndContinueDebuggerService? remoteDebuggeeModuleMetadataProvider = null; var debuggingSession = mockEncService.StartDebuggingSessionImpl = (solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics) => { Assert.Equal("proj", solution.Projects.Single().Name); AssertEx.Equal(new[] { document1.Id }, captureMatchingDocuments); Assert.False(captureAllMatchingDocuments); Assert.True(reportDiagnostics); remoteDebuggeeModuleMetadataProvider = debuggerService; return new DebuggingSessionId(1); }; var sessionProxy = await proxy.StartDebuggingSessionAsync( localWorkspace.CurrentSolution, debuggerService: new MockManagedEditAndContinueDebuggerService() { IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForModule, "can't do enc"), GetActiveStatementsImpl = () => ImmutableArray.Create(as1) }, captureMatchingDocuments: ImmutableArray.Create(document1.Id), captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None).ConfigureAwait(false); Contract.ThrowIfNull(sessionProxy); // BreakStateEntered mockEncService.BreakStateEnteredImpl = (out ImmutableArray<DocumentId> documentsToReanalyze) => { documentsToReanalyze = ImmutableArray.Create(document.Id); }; await sessionProxy.BreakStateEnteredAsync(mockDiagnosticService, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id)); var activeStatement = (await remoteDebuggeeModuleMetadataProvider!.GetActiveStatementsAsync(CancellationToken.None).ConfigureAwait(false)).Single(); Assert.Equal(as1.ActiveInstruction, activeStatement.ActiveInstruction); Assert.Equal(as1.SourceSpan, activeStatement.SourceSpan); Assert.Equal(as1.Flags, activeStatement.Flags); var availability = await remoteDebuggeeModuleMetadataProvider!.GetAvailabilityAsync(moduleId1, CancellationToken.None).ConfigureAwait(false); Assert.Equal(new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForModule, "can't do enc"), availability); // HasChanges mockEncService.HasChangesImpl = (solution, activeStatementSpanProvider, sourceFilePath) => { Assert.Equal("proj", solution.Projects.Single().Name); Assert.Equal("test.cs", sourceFilePath); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result); return true; }; Assert.True(await sessionProxy.HasChangesAsync(localWorkspace.CurrentSolution, activeStatementSpanProvider, "test.cs", CancellationToken.None).ConfigureAwait(false)); // EmitSolutionUpdate var diagnosticDescriptor1 = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); mockEncService.EmitSolutionUpdateImpl = (solution, activeStatementSpanProvider) => { var project = solution.Projects.Single(); Assert.Equal("proj", project.Name); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result); var deltas = ImmutableArray.Create(new ManagedModuleUpdate( module: moduleId1, ilDelta: ImmutableArray.Create<byte>(1, 2), metadataDelta: ImmutableArray.Create<byte>(3, 4), pdbDelta: ImmutableArray.Create<byte>(5, 6), updatedMethods: ImmutableArray.Create(0x06000001), updatedTypes: ImmutableArray.Create(0x02000001), sequencePoints: ImmutableArray.Create(new SequencePointUpdates("file.cs", ImmutableArray.Create(new SourceLineUpdate(1, 2)))), activeStatements: ImmutableArray.Create(new ManagedActiveStatementUpdate(instructionId1.Method.Method, instructionId1.ILOffset, span1.ToSourceSpan())), exceptionRegions: ImmutableArray.Create(exceptionRegionUpdate1))); var syntaxTree = project.Documents.Single().GetSyntaxTreeSynchronously(CancellationToken.None)!; var documentDiagnostic = Diagnostic.Create(diagnosticDescriptor1, Location.Create(syntaxTree, TextSpan.FromBounds(1, 2)), new[] { "doc", "some error" }); var projectDiagnostic = Diagnostic.Create(diagnosticDescriptor1, Location.None, new[] { "proj", "some error" }); var updates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Ready, deltas); var diagnostics = ImmutableArray.Create((project.Id, ImmutableArray.Create(documentDiagnostic, projectDiagnostic))); var documentsWithRudeEdits = ImmutableArray.Create((document1.Id, ImmutableArray<RudeEditDiagnostic>.Empty)); return new(updates, diagnostics, documentsWithRudeEdits); }; var (updates, _, _) = await sessionProxy.EmitSolutionUpdateAsync(localWorkspace.CurrentSolution, activeStatementSpanProvider, mockDiagnosticService, diagnosticUpdateSource, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document1.Id)); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Equal(1, emitDiagnosticsClearedCount); emitDiagnosticsClearedCount = 0; AssertEx.Equal(new[] { $"[{project.Id}] Error ENC1001: test.cs(0, 1, 0, 2): {string.Format(FeaturesResources.ErrorReadingFile, "doc", "some error")}", $"[{project.Id}] Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "proj", "some error")}" }, emitDiagnosticsUpdated.Select(update => { var d = update.GetPushDiagnostics(localWorkspace, InternalDiagnosticsOptions.NormalDiagnosticMode).Single(); return $"[{d.ProjectId}] {d.Severity} {d.Id}:" + (d.DataLocation != null ? $" {d.DataLocation.OriginalFilePath}({d.DataLocation.OriginalStartLine}, {d.DataLocation.OriginalStartColumn}, {d.DataLocation.OriginalEndLine}, {d.DataLocation.OriginalEndColumn}):" : "") + $" {d.Message}"; })); emitDiagnosticsUpdated.Clear(); var delta = updates.Updates.Single(); Assert.Equal(moduleId1, delta.Module); AssertEx.Equal(new byte[] { 1, 2 }, delta.ILDelta); AssertEx.Equal(new byte[] { 3, 4 }, delta.MetadataDelta); AssertEx.Equal(new byte[] { 5, 6 }, delta.PdbDelta); AssertEx.Equal(new[] { 0x06000001 }, delta.UpdatedMethods); AssertEx.Equal(new[] { 0x02000001 }, delta.UpdatedTypes); var lineEdit = delta.SequencePoints.Single(); Assert.Equal("file.cs", lineEdit.FileName); AssertEx.Equal(new[] { new SourceLineUpdate(1, 2) }, lineEdit.LineUpdates); Assert.Equal(exceptionRegionUpdate1, delta.ExceptionRegions.Single()); var activeStatements = delta.ActiveStatements.Single(); Assert.Equal(instructionId1.Method.Method, activeStatements.Method); Assert.Equal(instructionId1.ILOffset, activeStatements.ILOffset); Assert.Equal(span1, activeStatements.NewSpan.ToLinePositionSpan()); // CommitSolutionUpdate mockEncService.CommitSolutionUpdateImpl = (out ImmutableArray<DocumentId> documentsToReanalyze) => { documentsToReanalyze = ImmutableArray.Create(document.Id); }; await sessionProxy.CommitSolutionUpdateAsync(mockDiagnosticService, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id)); // DiscardSolutionUpdate var called = false; mockEncService.DiscardSolutionUpdateImpl = () => called = true; await sessionProxy.DiscardSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); Assert.True(called); // GetCurrentActiveStatementPosition mockEncService.GetCurrentActiveStatementPositionImpl = (solution, activeStatementSpanProvider, instructionId) => { Assert.Equal("proj", solution.Projects.Single().Name); Assert.Equal(instructionId1, instructionId); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result); return new LinePositionSpan(new LinePosition(1, 2), new LinePosition(1, 5)); }; Assert.Equal(span1, await sessionProxy.GetCurrentActiveStatementPositionAsync( localWorkspace.CurrentSolution, activeStatementSpanProvider, instructionId1, CancellationToken.None).ConfigureAwait(false)); // IsActiveStatementInExceptionRegion mockEncService.IsActiveStatementInExceptionRegionImpl = (solution, instructionId) => { Assert.Equal(instructionId1, instructionId); return true; }; Assert.True(await sessionProxy.IsActiveStatementInExceptionRegionAsync(localWorkspace.CurrentSolution, instructionId1, CancellationToken.None).ConfigureAwait(false)); // GetBaseActiveStatementSpans var activeStatementSpan1 = new ActiveStatementSpan(0, span1, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.PartiallyExecuted, unmappedDocumentId: document1.Id); mockEncService.GetBaseActiveStatementSpansImpl = (solution, documentIds) => { AssertEx.Equal(new[] { document1.Id }, documentIds); return ImmutableArray.Create(ImmutableArray.Create(activeStatementSpan1)); }; var baseActiveSpans = await sessionProxy.GetBaseActiveStatementSpansAsync(localWorkspace.CurrentSolution, ImmutableArray.Create(document1.Id), CancellationToken.None).ConfigureAwait(false); Assert.Equal(activeStatementSpan1, baseActiveSpans.Single().Single()); // GetDocumentActiveStatementSpans mockEncService.GetAdjustedActiveStatementSpansImpl = (document, activeStatementSpanProvider) => { Assert.Equal("test.cs", document.Name); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document.Id, "test.cs", CancellationToken.None).AsTask().Result); return ImmutableArray.Create(activeStatementSpan1); }; var documentActiveSpans = await sessionProxy.GetAdjustedActiveStatementSpansAsync(document1, activeStatementSpanProvider, CancellationToken.None).ConfigureAwait(false); Assert.Equal(activeStatementSpan1, documentActiveSpans.Single()); // GetDocumentActiveStatementSpans (default array) mockEncService.GetAdjustedActiveStatementSpansImpl = (document, _) => default; documentActiveSpans = await sessionProxy.GetAdjustedActiveStatementSpansAsync(document1, activeStatementSpanProvider, CancellationToken.None).ConfigureAwait(false); Assert.True(documentActiveSpans.IsDefault); // OnSourceFileUpdatedAsync called = false; mockEncService.OnSourceFileUpdatedImpl = updatedDocument => { Assert.Equal(document.Id, updatedDocument.Id); called = true; }; await proxy.OnSourceFileUpdatedAsync(document, CancellationToken.None).ConfigureAwait(false); Assert.True(called); // EndDebuggingSession mockEncService.EndDebuggingSessionImpl = (out ImmutableArray<DocumentId> documentsToReanalyze) => { documentsToReanalyze = ImmutableArray.Create(document.Id); }; await sessionProxy.EndDebuggingSessionAsync(solution, diagnosticUpdateSource, mockDiagnosticService, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id)); Assert.Equal(1, emitDiagnosticsClearedCount); emitDiagnosticsClearedCount = 0; Assert.Empty(emitDiagnosticsUpdated); } } }
1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Features/Core/Portable/EditAndContinue/Remote/RemoteDebuggingSessionProxy.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class RemoteDebuggingSessionProxy : IActiveStatementSpanProvider, IDisposable { private readonly IDisposable? _connection; private readonly DebuggingSessionId _sessionId; private readonly Workspace _workspace; public RemoteDebuggingSessionProxy(Workspace workspace, IDisposable? connection, DebuggingSessionId sessionId) { _connection = connection; _sessionId = sessionId; _workspace = workspace; } public void Dispose() { _connection?.Dispose(); } private IEditAndContinueWorkspaceService GetLocalService() => _workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); public async ValueTask BreakStateEnteredAsync(IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().BreakStateEntered(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.BreakStateEnteredAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask EndDebuggingSessionAsync(EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().EndDebuggingSession(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.EndDebuggingSessionAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); Dispose(); } public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().HasChangesAsync(_sessionId, solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.HasChangesAsync(solutionInfo, callbackId, _sessionId, sourceFilePath, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : true; } public async ValueTask<( ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>)> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, CancellationToken cancellationToken) { ManagedModuleUpdates moduleUpdates; ImmutableArray<DiagnosticData> diagnosticData; ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> rudeEdits; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { var results = await GetLocalService().EmitSolutionUpdateAsync(_sessionId, solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); moduleUpdates = results.ModuleUpdates; diagnosticData = results.GetDiagnosticData(solution); rudeEdits = results.RudeEdits; } else { var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, EmitSolutionUpdateResults.Data>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.EmitSolutionUpdateAsync(solutionInfo, callbackId, _sessionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); if (result.HasValue) { moduleUpdates = result.Value.ModuleUpdates; diagnosticData = result.Value.Diagnostics; rudeEdits = result.Value.RudeEdits; } else { moduleUpdates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); diagnosticData = ImmutableArray<DiagnosticData>.Empty; rudeEdits = ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>.Empty; } } // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: rudeEdits.Select(d => d.DocumentId)); // report emit/apply diagnostics: diagnosticUpdateSource.ReportDiagnostics(_workspace, solution, diagnosticData); return (moduleUpdates, diagnosticData, rudeEdits); } public async ValueTask CommitSolutionUpdateAsync(IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().CommitSolutionUpdate(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.CommitSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask DiscardSolutionUpdateAsync(CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().DiscardSolutionUpdate(_sessionId); return; } await client.TryInvokeAsync<IRemoteEditAndContinueService>( (service, cancellationToken) => service.DiscardSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetCurrentActiveStatementPositionAsync(_sessionId, solution, activeStatementSpanProvider, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, LinePositionSpan?>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetCurrentActiveStatementPositionAsync(solutionInfo, callbackId, _sessionId, instructionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().IsActiveStatementInExceptionRegionAsync(_sessionId, solution, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool?>( solution, (service, solutionInfo, cancellationToken) => service.IsActiveStatementInExceptionRegionAsync(solutionInfo, _sessionId, instructionId, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetBaseActiveStatementSpansAsync(_sessionId, solution, documentIds, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>( solution, (service, solutionInfo, cancellationToken) => service.GetBaseActiveStatementSpansAsync(solutionInfo, _sessionId, documentIds, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ImmutableArray<ActiveStatementSpan>>.Empty; } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetAdjustedActiveStatementSpansAsync(_sessionId, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ActiveStatementSpan>>( document.Project.Solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetAdjustedActiveStatementSpansAsync(solutionInfo, callbackId, _sessionId, document.Id, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ActiveStatementSpan>.Empty; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class RemoteDebuggingSessionProxy : IActiveStatementSpanProvider, IDisposable { private readonly IDisposable? _connection; private readonly DebuggingSessionId _sessionId; private readonly Workspace _workspace; public RemoteDebuggingSessionProxy(Workspace workspace, IDisposable? connection, DebuggingSessionId sessionId) { _connection = connection; _sessionId = sessionId; _workspace = workspace; } public void Dispose() { _connection?.Dispose(); } private IEditAndContinueWorkspaceService GetLocalService() => _workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); public async ValueTask BreakStateEnteredAsync(IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().BreakStateEntered(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.BreakStateEnteredAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask EndDebuggingSessionAsync(Solution compileTimeSolution, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().EndDebuggingSession(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.EndDebuggingSessionAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } var designTimeDocumentsToReanalyze = await CompileTimeSolutionProvider.GetDesignTimeDocumentsAsync( compileTimeSolution, documentsToReanalyze, designTimeSolution: _workspace.CurrentSolution, cancellationToken).ConfigureAwait(false); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: designTimeDocumentsToReanalyze); // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); Dispose(); } public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().HasChangesAsync(_sessionId, solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.HasChangesAsync(solutionInfo, callbackId, _sessionId, sourceFilePath, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : true; } public async ValueTask<( ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>)> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, CancellationToken cancellationToken) { ManagedModuleUpdates moduleUpdates; ImmutableArray<DiagnosticData> diagnosticData; ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> rudeEdits; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { var results = await GetLocalService().EmitSolutionUpdateAsync(_sessionId, solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); moduleUpdates = results.ModuleUpdates; diagnosticData = results.GetDiagnosticData(solution); rudeEdits = results.RudeEdits; } else { var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, EmitSolutionUpdateResults.Data>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.EmitSolutionUpdateAsync(solutionInfo, callbackId, _sessionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); if (result.HasValue) { moduleUpdates = result.Value.ModuleUpdates; diagnosticData = result.Value.Diagnostics; rudeEdits = result.Value.RudeEdits; } else { moduleUpdates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); diagnosticData = ImmutableArray<DiagnosticData>.Empty; rudeEdits = ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>.Empty; } } // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: rudeEdits.Select(d => d.DocumentId)); // report emit/apply diagnostics: diagnosticUpdateSource.ReportDiagnostics(_workspace, solution, diagnosticData); return (moduleUpdates, diagnosticData, rudeEdits); } public async ValueTask CommitSolutionUpdateAsync(IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().CommitSolutionUpdate(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.CommitSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask DiscardSolutionUpdateAsync(CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().DiscardSolutionUpdate(_sessionId); return; } await client.TryInvokeAsync<IRemoteEditAndContinueService>( (service, cancellationToken) => service.DiscardSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetCurrentActiveStatementPositionAsync(_sessionId, solution, activeStatementSpanProvider, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, LinePositionSpan?>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetCurrentActiveStatementPositionAsync(solutionInfo, callbackId, _sessionId, instructionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().IsActiveStatementInExceptionRegionAsync(_sessionId, solution, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool?>( solution, (service, solutionInfo, cancellationToken) => service.IsActiveStatementInExceptionRegionAsync(solutionInfo, _sessionId, instructionId, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetBaseActiveStatementSpansAsync(_sessionId, solution, documentIds, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>( solution, (service, solutionInfo, cancellationToken) => service.GetBaseActiveStatementSpansAsync(solutionInfo, _sessionId, documentIds, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ImmutableArray<ActiveStatementSpan>>.Empty; } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetAdjustedActiveStatementSpansAsync(_sessionId, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ActiveStatementSpan>>( document.Project.Solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetAdjustedActiveStatementSpansAsync(solutionInfo, callbackId, _sessionId, document.Id, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ActiveStatementSpan>.Empty; } } }
1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Features/Core/Portable/Workspace/CompileTimeSolutionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices { /// <summary> /// Provides a compile-time view of the current workspace solution. /// Workaround for Razor projects which generate both design-time and compile-time source files. /// TODO: remove https://github.com/dotnet/roslyn/issues/51678 /// </summary> internal sealed class CompileTimeSolutionProvider : ICompileTimeSolutionProvider { [ExportWorkspaceServiceFactory(typeof(ICompileTimeSolutionProvider), WorkspaceKind.Host), Shared] private sealed class Factory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService? CreateService(HostWorkspaceServices workspaceServices) => new CompileTimeSolutionProvider(workspaceServices.Workspace); } private const string RazorEncConfigFileName = "RazorSourceGenerator.razorencconfig"; private readonly object _gate = new(); private Solution? _lazyCompileTimeSolution; private int? _correspondingDesignTimeSolutionVersion; public CompileTimeSolutionProvider(Workspace workspace) { workspace.WorkspaceChanged += (s, e) => { if (e.Kind is WorkspaceChangeKind.SolutionCleared or WorkspaceChangeKind.SolutionRemoved) { lock (_gate) { _lazyCompileTimeSolution = null; _correspondingDesignTimeSolutionVersion = null; } } }; } private static bool IsRazorAnalyzerConfig(TextDocumentState documentState) => documentState.FilePath != null && documentState.FilePath.EndsWith(RazorEncConfigFileName, StringComparison.OrdinalIgnoreCase); public Solution GetCompileTimeSolution(Solution designTimeSolution) { lock (_gate) { // Design time solution hasn't changed since we calculated the last compile-time solution: if (designTimeSolution.WorkspaceVersion == _correspondingDesignTimeSolutionVersion) { Contract.ThrowIfNull(_lazyCompileTimeSolution); return _lazyCompileTimeSolution; } using var _1 = ArrayBuilder<DocumentId>.GetInstance(out var configIdsToRemove); using var _2 = ArrayBuilder<DocumentId>.GetInstance(out var documentIdsToRemove); var compileTimeSolution = designTimeSolution; foreach (var (_, projectState) in designTimeSolution.State.ProjectStates) { var anyConfigs = false; foreach (var (_, configState) in projectState.AnalyzerConfigDocumentStates.States) { if (IsRazorAnalyzerConfig(configState)) { configIdsToRemove.Add(configState.Id); anyConfigs = true; } } // only remove design-time only documents when source-generated ones replace them if (anyConfigs) { foreach (var (_, documentState) in projectState.DocumentStates.States) { if (documentState.Attributes.DesignTimeOnly) { documentIdsToRemove.Add(documentState.Id); } } } } _lazyCompileTimeSolution = designTimeSolution .RemoveAnalyzerConfigDocuments(configIdsToRemove.ToImmutable()) .RemoveDocuments(documentIdsToRemove.ToImmutable()); _correspondingDesignTimeSolutionVersion = designTimeSolution.WorkspaceVersion; return _lazyCompileTimeSolution; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// Provides a compile-time view of the current workspace solution. /// Workaround for Razor projects which generate both design-time and compile-time source files. /// TODO: remove https://github.com/dotnet/roslyn/issues/51678 /// </summary> internal sealed class CompileTimeSolutionProvider : ICompileTimeSolutionProvider { [ExportWorkspaceServiceFactory(typeof(ICompileTimeSolutionProvider), WorkspaceKind.Host), Shared] private sealed class Factory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService? CreateService(HostWorkspaceServices workspaceServices) => new CompileTimeSolutionProvider(workspaceServices.Workspace); } private const string RazorEncConfigFileName = "RazorSourceGenerator.razorencconfig"; private const string RazorSourceGeneratorAssemblyName = "Microsoft.NET.Sdk.Razor.SourceGenerators"; private const string RazorSourceGeneratorTypeName = "Microsoft.NET.Sdk.Razor.SourceGenerators.RazorSourceGenerator"; private static readonly string s_razorSourceGeneratorFileNamePrefix = Path.Combine(RazorSourceGeneratorAssemblyName, RazorSourceGeneratorTypeName); private readonly object _gate = new(); private Solution? _lazyCompileTimeSolution; private int? _correspondingDesignTimeSolutionVersion; public CompileTimeSolutionProvider(Workspace workspace) { workspace.WorkspaceChanged += (s, e) => { if (e.Kind is WorkspaceChangeKind.SolutionCleared or WorkspaceChangeKind.SolutionRemoved) { lock (_gate) { _lazyCompileTimeSolution = null; _correspondingDesignTimeSolutionVersion = null; } } }; } private static bool IsRazorAnalyzerConfig(TextDocumentState documentState) => documentState.FilePath != null && documentState.FilePath.EndsWith(RazorEncConfigFileName, StringComparison.OrdinalIgnoreCase); public Solution GetCompileTimeSolution(Solution designTimeSolution) { lock (_gate) { // Design time solution hasn't changed since we calculated the last compile-time solution: if (designTimeSolution.WorkspaceVersion == _correspondingDesignTimeSolutionVersion) { Contract.ThrowIfNull(_lazyCompileTimeSolution); return _lazyCompileTimeSolution; } using var _1 = ArrayBuilder<DocumentId>.GetInstance(out var configIdsToRemove); using var _2 = ArrayBuilder<DocumentId>.GetInstance(out var documentIdsToRemove); var compileTimeSolution = designTimeSolution; foreach (var (_, projectState) in designTimeSolution.State.ProjectStates) { var anyConfigs = false; foreach (var (_, configState) in projectState.AnalyzerConfigDocumentStates.States) { if (IsRazorAnalyzerConfig(configState)) { configIdsToRemove.Add(configState.Id); anyConfigs = true; } } // only remove design-time only documents when source-generated ones replace them if (anyConfigs) { foreach (var (_, documentState) in projectState.DocumentStates.States) { if (documentState.Attributes.DesignTimeOnly) { documentIdsToRemove.Add(documentState.Id); } } } } _lazyCompileTimeSolution = designTimeSolution .RemoveAnalyzerConfigDocuments(configIdsToRemove.ToImmutable()) .RemoveDocuments(documentIdsToRemove.ToImmutable()); _correspondingDesignTimeSolutionVersion = designTimeSolution.WorkspaceVersion; return _lazyCompileTimeSolution; } } // Copied from // https://github.com/dotnet/sdk/blob/main/src/RazorSdk/SourceGenerators/RazorSourceGenerator.Helpers.cs#L32 private static string GetIdentifierFromPath(string filePath) { var builder = new StringBuilder(filePath.Length); for (var i = 0; i < filePath.Length; i++) { switch (filePath[i]) { case ':' or '\\' or '/': case char ch when !char.IsLetterOrDigit(ch): builder.Append('_'); break; default: builder.Append(filePath[i]); break; } } return builder.ToString(); } private static bool IsRazorDesignTimeDocument(DocumentState documentState) => documentState.Attributes.DesignTimeOnly && documentState.FilePath?.EndsWith(".razor.g.cs") == true; internal static async Task<Document?> TryGetCompileTimeDocumentAsync( Document designTimeDocument, Solution compileTimeSolution, CancellationToken cancellationToken, string? generatedDocumentPathPrefix = null) { var compileTimeDocument = await compileTimeSolution.GetDocumentAsync(designTimeDocument.Id, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (compileTimeDocument != null) { return compileTimeDocument; } if (!IsRazorDesignTimeDocument(designTimeDocument.DocumentState)) { return null; } var relativeDocumentPath = GetRelativeDocumentPath(PathUtilities.GetDirectoryName(designTimeDocument.Project.FilePath)!, designTimeDocument.FilePath!); var generatedDocumentPath = Path.Combine(generatedDocumentPathPrefix ?? s_razorSourceGeneratorFileNamePrefix, GetIdentifierFromPath(relativeDocumentPath)) + ".cs"; var sourceGeneratedDocuments = await compileTimeSolution.GetRequiredProject(designTimeDocument.Project.Id).GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false); return sourceGeneratedDocuments.SingleOrDefault(d => d.FilePath == generatedDocumentPath); } private static string GetRelativeDocumentPath(string projectDirectory, string designTimeDocumentFilePath) => Path.Combine("\\", PathUtilities.GetRelativePath(projectDirectory, designTimeDocumentFilePath)[..^".g.cs".Length]); private static bool HasMatchingFilePath(string designTimeDocumentFilePath, string designTimeProjectDirectory, string compileTimeFilePath) => PathUtilities.GetFileName(compileTimeFilePath, includeExtension: false) == GetIdentifierFromPath(GetRelativeDocumentPath(designTimeProjectDirectory, designTimeDocumentFilePath)); internal static async Task<ImmutableArray<DocumentId>> GetDesignTimeDocumentsAsync( Solution compileTimeSolution, ImmutableArray<DocumentId> compileTimeDocumentIds, Solution designTimeSolution, CancellationToken cancellationToken, string? generatedDocumentPathPrefix = null) { using var _1 = ArrayBuilder<DocumentId>.GetInstance(out var result); using var _2 = PooledDictionary<ProjectId, ArrayBuilder<string>>.GetInstance(out var compileTimeFilePathsByProject); generatedDocumentPathPrefix ??= s_razorSourceGeneratorFileNamePrefix; foreach (var compileTimeDocumentId in compileTimeDocumentIds) { if (designTimeSolution.ContainsDocument(compileTimeDocumentId)) { result.Add(compileTimeDocumentId); } else { var compileTimeDocument = await compileTimeSolution.GetTextDocumentAsync(compileTimeDocumentId, cancellationToken).ConfigureAwait(false); var filePath = compileTimeDocument?.State.FilePath; if (filePath?.StartsWith(generatedDocumentPathPrefix) == true) { compileTimeFilePathsByProject.MultiAdd(compileTimeDocumentId.ProjectId, filePath); } } } if (result.Count == compileTimeDocumentIds.Length) { Debug.Assert(compileTimeFilePathsByProject.Count == 0); return compileTimeDocumentIds; } foreach (var (projectId, compileTimeFilePaths) in compileTimeFilePathsByProject) { var designTimeProjectState = designTimeSolution.GetProjectState(projectId); if (designTimeProjectState == null) { continue; } var designTimeProjectDirectory = PathUtilities.GetDirectoryName(designTimeProjectState.FilePath)!; foreach (var (_, designTimeDocumentState) in designTimeProjectState.DocumentStates.States) { if (IsRazorDesignTimeDocument(designTimeDocumentState) && compileTimeFilePaths.Any(compileTimeFilePath => HasMatchingFilePath(designTimeDocumentState.FilePath!, designTimeProjectDirectory, compileTimeFilePath))) { result.Add(designTimeDocumentState.Id); } } } compileTimeFilePathsByProject.FreeValues(); return result.ToImmutable(); } } }
1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/VisualStudio/Core/Def/Implementation/EditAndContinue/ManagedEditAndContinueLanguageService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.EditAndContinue { [Shared] [Export(typeof(IManagedEditAndContinueLanguageService))] [ExportMetadata("UIContext", Guids.EncCapableProjectExistsInWorkspaceUIContextString)] internal sealed class ManagedEditAndContinueLanguageService : IManagedEditAndContinueLanguageService { private readonly RemoteEditAndContinueServiceProxy _proxy; private readonly IDebuggingWorkspaceService _debuggingService; private readonly IActiveStatementTrackingService _activeStatementTrackingService; private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly EditAndContinueDiagnosticUpdateSource _diagnosticUpdateSource; private readonly IManagedEditAndContinueDebuggerService _debuggerService; private RemoteDebuggingSessionProxy? _debuggingSession; private bool _disabled; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ManagedEditAndContinueLanguageService( VisualStudioWorkspace workspace, IManagedEditAndContinueDebuggerService debuggerService, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource) { _proxy = new RemoteEditAndContinueServiceProxy(workspace); _debuggingService = workspace.Services.GetRequiredService<IDebuggingWorkspaceService>(); _activeStatementTrackingService = workspace.Services.GetRequiredService<IActiveStatementTrackingService>(); _debuggerService = debuggerService; _diagnosticService = diagnosticService; _diagnosticUpdateSource = diagnosticUpdateSource; } private Solution GetCurrentCompileTimeSolution() => _proxy.Workspace.Services.GetRequiredService<ICompileTimeSolutionProvider>().GetCompileTimeSolution(_proxy.Workspace.CurrentSolution); private RemoteDebuggingSessionProxy GetDebuggingSession() { var debuggingSession = _debuggingSession; Contract.ThrowIfNull(debuggingSession); return debuggingSession; } /// <summary> /// Called by the debugger when a debugging session starts and managed debugging is being used. /// </summary> public async Task StartDebuggingAsync(DebugSessionFlags flags, CancellationToken cancellationToken) { _debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run); _disabled = (flags & DebugSessionFlags.EditAndContinueDisabled) != 0; if (_disabled) { return; } try { var solution = GetCurrentCompileTimeSolution(); var openedDocumentIds = _proxy.Workspace.GetOpenDocumentIds().ToImmutableArray(); _debuggingSession = await _proxy.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: openedDocumentIds, captureAllMatchingDocuments: false, reportDiagnostics: true, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { } // the service failed, error has been reported - disable further operations _disabled = _debuggingSession == null; } public async Task EnterBreakStateAsync(CancellationToken cancellationToken) { _debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Break); if (_disabled) { return; } var solution = GetCurrentCompileTimeSolution(); var session = GetDebuggingSession(); try { await session.BreakStateEnteredAsync(_diagnosticService, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = true; return; } // Start tracking after we entered break state so that break-state session is active. // This is potentially costly operation but entering break state is non-blocking so it should be ok to await. await _activeStatementTrackingService.StartTrackingAsync(solution, session, cancellationToken).ConfigureAwait(false); } public Task ExitBreakStateAsync(CancellationToken cancellationToken) { _debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run); if (!_disabled) { _activeStatementTrackingService.EndTracking(); } return Task.CompletedTask; } public async Task CommitUpdatesAsync(CancellationToken cancellationToken) { try { Contract.ThrowIfTrue(_disabled); await GetDebuggingSession().CommitSolutionUpdateAsync(_diagnosticService, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } public async Task DiscardUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { return; } try { await GetDebuggingSession().DiscardSolutionUpdateAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } public async Task StopDebuggingAsync(CancellationToken cancellationToken) { _debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Design); if (_disabled) { return; } try { await GetDebuggingSession().EndDebuggingSessionAsync(_diagnosticUpdateSource, _diagnosticService, cancellationToken).ConfigureAwait(false); _debuggingSession = null; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = true; } } private ActiveStatementSpanProvider GetActiveStatementSpanProvider(Solution solution) => new((documentId, filePath, cancellationToken) => _activeStatementTrackingService.GetSpansAsync(solution, documentId, filePath, cancellationToken)); /// <summary> /// Returns true if any changes have been made to the source since the last changes had been applied. /// </summary> public async Task<bool> HasChangesAsync(string? sourceFilePath, CancellationToken cancellationToken) { try { var debuggingSession = _debuggingSession; if (debuggingSession == null) { return false; } var solution = GetCurrentCompileTimeSolution(); var activeStatementSpanProvider = GetActiveStatementSpanProvider(solution); return await debuggingSession.HasChangesAsync(solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return true; } } public async Task<ManagedModuleUpdates> GetManagedModuleUpdatesAsync(CancellationToken cancellationToken) { try { var solution = GetCurrentCompileTimeSolution(); var activeStatementSpanProvider = GetActiveStatementSpanProvider(solution); var (updates, _, _) = await GetDebuggingSession().EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, _diagnosticService, _diagnosticUpdateSource, cancellationToken).ConfigureAwait(false); return updates; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); } } public async Task<SourceSpan?> GetCurrentActiveStatementPositionAsync(ManagedInstructionId instruction, CancellationToken cancellationToken) { try { var solution = GetCurrentCompileTimeSolution(); var activeStatementSpanProvider = new ActiveStatementSpanProvider((documentId, filePath, cancellationToken) => _activeStatementTrackingService.GetSpansAsync(solution, documentId, filePath, cancellationToken)); var span = await GetDebuggingSession().GetCurrentActiveStatementPositionAsync(solution, activeStatementSpanProvider, instruction, cancellationToken).ConfigureAwait(false); return span?.ToSourceSpan(); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } public async Task<bool?> IsActiveStatementInExceptionRegionAsync(ManagedInstructionId instruction, CancellationToken cancellationToken) { try { var solution = GetCurrentCompileTimeSolution(); return await GetDebuggingSession().IsActiveStatementInExceptionRegionAsync(solution, instruction, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.EditAndContinue { [Shared] [Export(typeof(IManagedEditAndContinueLanguageService))] [ExportMetadata("UIContext", Guids.EncCapableProjectExistsInWorkspaceUIContextString)] internal sealed class ManagedEditAndContinueLanguageService : IManagedEditAndContinueLanguageService { private readonly RemoteEditAndContinueServiceProxy _proxy; private readonly IDebuggingWorkspaceService _debuggingService; private readonly IActiveStatementTrackingService _activeStatementTrackingService; private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly EditAndContinueDiagnosticUpdateSource _diagnosticUpdateSource; private readonly IManagedEditAndContinueDebuggerService _debuggerService; private RemoteDebuggingSessionProxy? _debuggingSession; private bool _disabled; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ManagedEditAndContinueLanguageService( VisualStudioWorkspace workspace, IManagedEditAndContinueDebuggerService debuggerService, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource) { _proxy = new RemoteEditAndContinueServiceProxy(workspace); _debuggingService = workspace.Services.GetRequiredService<IDebuggingWorkspaceService>(); _activeStatementTrackingService = workspace.Services.GetRequiredService<IActiveStatementTrackingService>(); _debuggerService = debuggerService; _diagnosticService = diagnosticService; _diagnosticUpdateSource = diagnosticUpdateSource; } private Solution GetCurrentCompileTimeSolution() => _proxy.Workspace.Services.GetRequiredService<ICompileTimeSolutionProvider>().GetCompileTimeSolution(_proxy.Workspace.CurrentSolution); private RemoteDebuggingSessionProxy GetDebuggingSession() { var debuggingSession = _debuggingSession; Contract.ThrowIfNull(debuggingSession); return debuggingSession; } /// <summary> /// Called by the debugger when a debugging session starts and managed debugging is being used. /// </summary> public async Task StartDebuggingAsync(DebugSessionFlags flags, CancellationToken cancellationToken) { _debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run); _disabled = (flags & DebugSessionFlags.EditAndContinueDisabled) != 0; if (_disabled) { return; } try { var solution = GetCurrentCompileTimeSolution(); var openedDocumentIds = _proxy.Workspace.GetOpenDocumentIds().ToImmutableArray(); _debuggingSession = await _proxy.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: openedDocumentIds, captureAllMatchingDocuments: false, reportDiagnostics: true, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { } // the service failed, error has been reported - disable further operations _disabled = _debuggingSession == null; } public async Task EnterBreakStateAsync(CancellationToken cancellationToken) { _debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Break); if (_disabled) { return; } var solution = GetCurrentCompileTimeSolution(); var session = GetDebuggingSession(); try { await session.BreakStateEnteredAsync(_diagnosticService, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = true; return; } // Start tracking after we entered break state so that break-state session is active. // This is potentially costly operation but entering break state is non-blocking so it should be ok to await. await _activeStatementTrackingService.StartTrackingAsync(solution, session, cancellationToken).ConfigureAwait(false); } public Task ExitBreakStateAsync(CancellationToken cancellationToken) { _debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run); if (!_disabled) { _activeStatementTrackingService.EndTracking(); } return Task.CompletedTask; } public async Task CommitUpdatesAsync(CancellationToken cancellationToken) { try { Contract.ThrowIfTrue(_disabled); await GetDebuggingSession().CommitSolutionUpdateAsync(_diagnosticService, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } public async Task DiscardUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { return; } try { await GetDebuggingSession().DiscardSolutionUpdateAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } public async Task StopDebuggingAsync(CancellationToken cancellationToken) { _debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Design); if (_disabled) { return; } try { var solution = GetCurrentCompileTimeSolution(); await GetDebuggingSession().EndDebuggingSessionAsync(solution, _diagnosticUpdateSource, _diagnosticService, cancellationToken).ConfigureAwait(false); _debuggingSession = null; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = true; } } private ActiveStatementSpanProvider GetActiveStatementSpanProvider(Solution solution) => new((documentId, filePath, cancellationToken) => _activeStatementTrackingService.GetSpansAsync(solution, documentId, filePath, cancellationToken)); /// <summary> /// Returns true if any changes have been made to the source since the last changes had been applied. /// </summary> public async Task<bool> HasChangesAsync(string? sourceFilePath, CancellationToken cancellationToken) { try { var debuggingSession = _debuggingSession; if (debuggingSession == null) { return false; } var solution = GetCurrentCompileTimeSolution(); var activeStatementSpanProvider = GetActiveStatementSpanProvider(solution); return await debuggingSession.HasChangesAsync(solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return true; } } public async Task<ManagedModuleUpdates> GetManagedModuleUpdatesAsync(CancellationToken cancellationToken) { try { var solution = GetCurrentCompileTimeSolution(); var activeStatementSpanProvider = GetActiveStatementSpanProvider(solution); var (updates, _, _) = await GetDebuggingSession().EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, _diagnosticService, _diagnosticUpdateSource, cancellationToken).ConfigureAwait(false); return updates; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); } } public async Task<SourceSpan?> GetCurrentActiveStatementPositionAsync(ManagedInstructionId instruction, CancellationToken cancellationToken) { try { var solution = GetCurrentCompileTimeSolution(); var activeStatementSpanProvider = new ActiveStatementSpanProvider((documentId, filePath, cancellationToken) => _activeStatementTrackingService.GetSpansAsync(solution, documentId, filePath, cancellationToken)); var span = await GetDebuggingSession().GetCurrentActiveStatementPositionAsync(solution, activeStatementSpanProvider, instruction, cancellationToken).ConfigureAwait(false); return span?.ToSourceSpan(); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } public async Task<bool?> IsActiveStatementInExceptionRegionAsync(ManagedInstructionId instruction, CancellationToken cancellationToken) { try { var solution = GetCurrentCompileTimeSolution(); return await GetDebuggingSession().IsActiveStatementInExceptionRegionAsync(solution, instruction, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } } }
1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/VisualStudio/Core/Def/Implementation/EditAndContinue/ManagedHotReloadLanguageService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Microsoft.VisualStudio.Debugger.Contracts.HotReload; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.EditAndContinue { [Shared] [Export(typeof(IManagedHotReloadLanguageService))] [ExportMetadata("UIContext", Guids.EncCapableProjectExistsInWorkspaceUIContextString)] internal sealed class ManagedHotReloadLanguageService : IManagedHotReloadLanguageService { private sealed class DebuggerService : IManagedEditAndContinueDebuggerService { private readonly IManagedHotReloadService _hotReloadService; public DebuggerService(IManagedHotReloadService hotReloadService) { _hotReloadService = hotReloadService; } public Task<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(CancellationToken cancellationToken) => Task.FromResult(ImmutableArray<ManagedActiveStatementDebugInfo>.Empty); public Task<ManagedEditAndContinueAvailability> GetAvailabilityAsync(Guid module, CancellationToken cancellationToken) => Task.FromResult(new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Available)); public Task<ImmutableArray<string>> GetCapabilitiesAsync(CancellationToken cancellationToken) => _hotReloadService.GetCapabilitiesAsync(cancellationToken).AsTask(); public Task PrepareModuleForUpdateAsync(Guid module, CancellationToken cancellationToken) => Task.CompletedTask; } private static readonly ActiveStatementSpanProvider s_solutionActiveStatementSpanProvider = (_, _, _) => ValueTaskFactory.FromResult(ImmutableArray<ActiveStatementSpan>.Empty); private readonly RemoteEditAndContinueServiceProxy _proxy; private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly EditAndContinueDiagnosticUpdateSource _diagnosticUpdateSource; private readonly DebuggerService _debuggerService; private RemoteDebuggingSessionProxy? _debuggingSession; private bool _disabled; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ManagedHotReloadLanguageService( VisualStudioWorkspace workspace, IManagedHotReloadService hotReloadService, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource) { _proxy = new RemoteEditAndContinueServiceProxy(workspace); _debuggerService = new DebuggerService(hotReloadService); _diagnosticService = diagnosticService; _diagnosticUpdateSource = diagnosticUpdateSource; } private RemoteDebuggingSessionProxy GetDebuggingSession() { var debuggingSession = _debuggingSession; Contract.ThrowIfNull(debuggingSession); return debuggingSession; } private Solution GetCurrentCompileTimeSolution() => _proxy.Workspace.Services.GetRequiredService<ICompileTimeSolutionProvider>().GetCompileTimeSolution(_proxy.Workspace.CurrentSolution); public async ValueTask StartSessionAsync(CancellationToken cancellationToken) { if (_disabled) { return; } try { var solution = GetCurrentCompileTimeSolution(); var openedDocumentIds = _proxy.Workspace.GetOpenDocumentIds().ToImmutableArray(); _debuggingSession = await _proxy.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: openedDocumentIds, captureAllMatchingDocuments: false, reportDiagnostics: true, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { } // the service failed, error has been reported - disable further operations _disabled = _debuggingSession == null; } public async ValueTask<ManagedHotReloadUpdates> GetUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { return new ManagedHotReloadUpdates(ImmutableArray<ManagedHotReloadUpdate>.Empty, ImmutableArray<ManagedHotReloadDiagnostic>.Empty); } try { var solution = GetCurrentCompileTimeSolution(); var (moduleUpdates, diagnosticData, rudeEdits) = await GetDebuggingSession().EmitSolutionUpdateAsync(solution, s_solutionActiveStatementSpanProvider, _diagnosticService, _diagnosticUpdateSource, cancellationToken).ConfigureAwait(false); var updates = moduleUpdates.Updates.SelectAsArray( update => new ManagedHotReloadUpdate(update.Module, update.ILDelta, update.MetadataDelta)); var diagnostics = await EmitSolutionUpdateResults.GetHotReloadDiagnosticsAsync(solution, diagnosticData, rudeEdits, cancellationToken).ConfigureAwait(false); return new ManagedHotReloadUpdates(updates, diagnostics); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(RudeEditKind.InternalError); // TODO: better error var diagnostic = new ManagedHotReloadDiagnostic( descriptor.Id, string.Format(descriptor.MessageFormat.ToString(), "", e.Message), ManagedHotReloadDiagnosticSeverity.Error, filePath: "", span: default); return new ManagedHotReloadUpdates(ImmutableArray<ManagedHotReloadUpdate>.Empty, ImmutableArray.Create(diagnostic)); } } public async ValueTask CommitUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { return; } try { await GetDebuggingSession().CommitSolutionUpdateAsync(_diagnosticService, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { _disabled = true; } } public async ValueTask DiscardUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { return; } try { await GetDebuggingSession().DiscardSolutionUpdateAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { _disabled = true; } } public async ValueTask EndSessionAsync(CancellationToken cancellationToken) { if (_disabled) { return; } try { await GetDebuggingSession().EndDebuggingSessionAsync(_diagnosticUpdateSource, _diagnosticService, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = true; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Microsoft.VisualStudio.Debugger.Contracts.HotReload; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.EditAndContinue { [Shared] [Export(typeof(IManagedHotReloadLanguageService))] [ExportMetadata("UIContext", Guids.EncCapableProjectExistsInWorkspaceUIContextString)] internal sealed class ManagedHotReloadLanguageService : IManagedHotReloadLanguageService { private sealed class DebuggerService : IManagedEditAndContinueDebuggerService { private readonly IManagedHotReloadService _hotReloadService; public DebuggerService(IManagedHotReloadService hotReloadService) { _hotReloadService = hotReloadService; } public Task<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(CancellationToken cancellationToken) => Task.FromResult(ImmutableArray<ManagedActiveStatementDebugInfo>.Empty); public Task<ManagedEditAndContinueAvailability> GetAvailabilityAsync(Guid module, CancellationToken cancellationToken) => Task.FromResult(new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Available)); public Task<ImmutableArray<string>> GetCapabilitiesAsync(CancellationToken cancellationToken) => _hotReloadService.GetCapabilitiesAsync(cancellationToken).AsTask(); public Task PrepareModuleForUpdateAsync(Guid module, CancellationToken cancellationToken) => Task.CompletedTask; } private static readonly ActiveStatementSpanProvider s_solutionActiveStatementSpanProvider = (_, _, _) => ValueTaskFactory.FromResult(ImmutableArray<ActiveStatementSpan>.Empty); private readonly RemoteEditAndContinueServiceProxy _proxy; private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly EditAndContinueDiagnosticUpdateSource _diagnosticUpdateSource; private readonly DebuggerService _debuggerService; private RemoteDebuggingSessionProxy? _debuggingSession; private bool _disabled; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ManagedHotReloadLanguageService( VisualStudioWorkspace workspace, IManagedHotReloadService hotReloadService, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource) { _proxy = new RemoteEditAndContinueServiceProxy(workspace); _debuggerService = new DebuggerService(hotReloadService); _diagnosticService = diagnosticService; _diagnosticUpdateSource = diagnosticUpdateSource; } private RemoteDebuggingSessionProxy GetDebuggingSession() { var debuggingSession = _debuggingSession; Contract.ThrowIfNull(debuggingSession); return debuggingSession; } private Solution GetCurrentCompileTimeSolution() => _proxy.Workspace.Services.GetRequiredService<ICompileTimeSolutionProvider>().GetCompileTimeSolution(_proxy.Workspace.CurrentSolution); public async ValueTask StartSessionAsync(CancellationToken cancellationToken) { if (_disabled) { return; } try { var solution = GetCurrentCompileTimeSolution(); var openedDocumentIds = _proxy.Workspace.GetOpenDocumentIds().ToImmutableArray(); _debuggingSession = await _proxy.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: openedDocumentIds, captureAllMatchingDocuments: false, reportDiagnostics: true, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { } // the service failed, error has been reported - disable further operations _disabled = _debuggingSession == null; } public async ValueTask<ManagedHotReloadUpdates> GetUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { return new ManagedHotReloadUpdates(ImmutableArray<ManagedHotReloadUpdate>.Empty, ImmutableArray<ManagedHotReloadDiagnostic>.Empty); } try { var solution = GetCurrentCompileTimeSolution(); var (moduleUpdates, diagnosticData, rudeEdits) = await GetDebuggingSession().EmitSolutionUpdateAsync(solution, s_solutionActiveStatementSpanProvider, _diagnosticService, _diagnosticUpdateSource, cancellationToken).ConfigureAwait(false); var updates = moduleUpdates.Updates.SelectAsArray( update => new ManagedHotReloadUpdate(update.Module, update.ILDelta, update.MetadataDelta)); var diagnostics = await EmitSolutionUpdateResults.GetHotReloadDiagnosticsAsync(solution, diagnosticData, rudeEdits, cancellationToken).ConfigureAwait(false); return new ManagedHotReloadUpdates(updates, diagnostics); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(RudeEditKind.InternalError); // TODO: better error var diagnostic = new ManagedHotReloadDiagnostic( descriptor.Id, string.Format(descriptor.MessageFormat.ToString(), "", e.Message), ManagedHotReloadDiagnosticSeverity.Error, filePath: "", span: default); return new ManagedHotReloadUpdates(ImmutableArray<ManagedHotReloadUpdate>.Empty, ImmutableArray.Create(diagnostic)); } } public async ValueTask CommitUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { return; } try { await GetDebuggingSession().CommitSolutionUpdateAsync(_diagnosticService, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { _disabled = true; } } public async ValueTask DiscardUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { return; } try { await GetDebuggingSession().DiscardSolutionUpdateAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { _disabled = true; } } public async ValueTask EndSessionAsync(CancellationToken cancellationToken) { if (_disabled) { return; } try { var solution = GetCurrentCompileTimeSolution(); await GetDebuggingSession().EndDebuggingSessionAsync(solution, _diagnosticUpdateSource, _diagnosticService, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = true; } } } }
1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Compilers/CSharp/Test/Semantic/Semantics/InitOnlyMemberTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { [CompilerTrait(CompilerFeature.InitOnlySetters)] public class InitOnlyMemberTests : CompilingTestBase { // Spec: https://github.com/dotnet/csharplang/blob/main/proposals/init.md // https://github.com/dotnet/roslyn/issues/44685 // test dynamic scenario // test whether reflection use property despite modreq? // test behavior of old compiler with modreq. For example VB [Fact] public void TestCSharp8() { string source = @" public class C { public string Property { get; init; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyEmitDiagnostics( // (4,35): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // public string Property { get; init; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "init").WithArguments("init-only setters", "9.0").WithLocation(4, 35) ); var property = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.True(property.SetMethod.IsInitOnly); IPropertySymbol publicProperty = property.GetPublicSymbol(); Assert.False(publicProperty.GetMethod.IsInitOnly); Assert.True(publicProperty.SetMethod.IsInitOnly); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionInObjectInitializer(bool useMetadataImage) { string lib_cs = @" public class C { public string Property { get; init; } public string Property2 { get; } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class D { void M() { _ = new C() { Property = string.Empty, Property2 = string.Empty }; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (6,23): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = new C() { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Property").WithArguments("init-only setters", "9.0").WithLocation(6, 23), // (6,48): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = new C() { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(6, 48) ); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionInNestedObjectInitializer(bool useMetadataImage) { string lib_cs = @" public class C { public string Property { get; init; } public string Property2 { get; } } public class Container { public C contained; } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class D { void M(C c) { _ = new Container() { contained = { Property = string.Empty, Property2 = string.Empty } }; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (6,45): error CS8852: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // _ = new Container() { contained = { Property = string.Empty, Property2 = string.Empty } }; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(6, 45), // (6,70): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = new Container() { contained = { Property = string.Empty, Property2 = string.Empty } }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(6, 70) ); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionInWithExpression(bool useMetadataImage) { string lib_cs = @" public record C { public string Property { get; init; } public string Property2 { get; } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class D { void M(C c) { _ = c with { Property = string.Empty, Property2 = string.Empty }; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (6,15): error CS8400: Feature 'records' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = c with { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "with").WithArguments("records", "9.0").WithLocation(6, 15), // (6,22): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = c with { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Property").WithArguments("init-only setters", "9.0").WithLocation(6, 22), // (6,47): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = c with { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(6, 47) ); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionInAssignment(bool useMetadataImage) { string lib_cs = @" public record C { public string Property { get; init; } public string Property2 { get; } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class D { void M(C c) { c.Property = string.Empty; c.Property2 = string.Empty; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (6,9): error CS8852: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = string.Empty; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(6, 9), // (7,9): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // c.Property2 = string.Empty; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "c.Property2").WithArguments("C.Property2").WithLocation(7, 9) ); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionInAttribute(bool useMetadataImage) { string lib_cs = @" public class TestAttribute : System.Attribute { public int Property { get; init; } public int Property2 { get; } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" [Test(Property = 42, Property2 = 43)] class C { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (2,7): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // [Test(Property = 42, Property2 = 43)] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Property = 42").WithArguments("init-only setters", "9.0").WithLocation(2, 7), // (2,22): error CS0617: 'Property2' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [Test(Property = 42, Property2 = 43)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "Property2").WithArguments("Property2").WithLocation(2, 22) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (2,22): error CS0617: 'Property2' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [Test(Property = 42, Property2 = 43)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "Property2").WithArguments("Property2").WithLocation(2, 22) ); } [Fact, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionWithinSameCompilation() { string source = @" class C { string Property { get; init; } string Property2 { get; } void M(C c) { _ = new C() { Property = string.Empty, Property2 = string.Empty }; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyEmitDiagnostics( // (4,28): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // string Property { get; init; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "init").WithArguments("init-only setters", "9.0").WithLocation(4, 28), // (9,48): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = new C() { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(9, 48) ); } [Fact, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionWithinSameCompilation_InAttribute() { string source = @" public class TestAttribute : System.Attribute { public int Property { get; init; } public int Property2 { get; } } [Test(Property = 42, Property2 = 43)] class C { } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyEmitDiagnostics( // (4,32): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // public int Property { get; init; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "init").WithArguments("init-only setters", "9.0").WithLocation(4, 32), // (8,22): error CS0617: 'Property2' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [Test(Property = 42, Property2 = 43)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "Property2").WithArguments("Property2").WithLocation(8, 22) ); } [Fact, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionFromCompilationReference() { string lib_cs = @" public class C { public string Property { get; init; } public string Property2 { get; } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular8, assemblyName: "lib"); string source = @" public class D { void M() { _ = new C() { Property = string.Empty, Property2 = string.Empty }; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { lib.ToMetadataReference() }, assemblyName: "comp"); comp.VerifyEmitDiagnostics( // (6,23): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = new C() { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Property").WithArguments("init-only setters", "9.0").WithLocation(6, 23), // (6,48): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = new C() { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(6, 48) ); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionWithDynamicArgument(bool useMetadataImage) { string lib_cs = @" public class C { public string Property { get; init; } public string Property2 { get; } public C(int i) { } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class D { void M(dynamic d) { _ = new C(d) { Property = string.Empty, Property2 = string.Empty }; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (6,24): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = new C(d) { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Property").WithArguments("init-only setters", "9.0").WithLocation(6, 24), // (6,49): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = new C(d) { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(6, 49) ); } [Fact] public void TestInitNotModifier() { string source = @" public class C { public string Property { get; init set; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,40): error CS8180: { or ; or => expected // public string Property { get; init set; } Diagnostic(ErrorCode.ERR_SemiOrLBraceOrArrowExpected, "set").WithLocation(4, 40), // (4,40): error CS1007: Property accessor already defined // public string Property { get; init set; } Diagnostic(ErrorCode.ERR_DuplicateAccessor, "set").WithLocation(4, 40) ); } [Fact] public void TestWithDuplicateAccessor() { string source = @" public class C { public string Property { set => throw null; init => throw null; } public string Property2 { init => throw null; set => throw null; } public string Property3 { init => throw null; init => throw null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,49): error CS1007: Property accessor already defined // public string Property { set => throw null; init => throw null; } Diagnostic(ErrorCode.ERR_DuplicateAccessor, "init").WithLocation(4, 49), // (5,51): error CS1007: Property accessor already defined // public string Property2 { init => throw null; set => throw null; } Diagnostic(ErrorCode.ERR_DuplicateAccessor, "set").WithLocation(5, 51), // (6,51): error CS1007: Property accessor already defined // public string Property3 { init => throw null; init => throw null; } Diagnostic(ErrorCode.ERR_DuplicateAccessor, "init").WithLocation(6, 51) ); var members = ((NamedTypeSymbol)comp.GlobalNamespace.GetMember("C")).GetMembers(); AssertEx.SetEqual(members.ToTestDisplayStrings(), new[] { "System.String C.Property { set; }", "void C.Property.set", "System.String C.Property2 { init; }", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.Property2.init", "System.String C.Property3 { init; }", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.Property3.init", "C..ctor()" }); var property = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property.SetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().SetMethod.IsInitOnly); var property2 = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property2"); Assert.True(property2.SetMethod.IsInitOnly); Assert.True(property2.GetPublicSymbol().SetMethod.IsInitOnly); var property3 = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property3"); Assert.True(property3.SetMethod.IsInitOnly); Assert.True(property3.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void InThisOrBaseConstructorInitializer() { string source = @" public class C { public string Property { init { throw null; } } public C() : this(Property = null) // 1 { } public C(string s) { } } public class Derived : C { public Derived() : base(Property = null) // 2 { } public Derived(int i) : base(base.Property = null) // 3 { } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (5,23): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // public C() : this(Property = null) // 1 Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(5, 23), // (15,29): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // public Derived() : base(Property = null) // 2 Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(15, 29), // (19,34): error CS1512: Keyword 'base' is not available in the current context // public Derived(int i) : base(base.Property = null) // 3 Diagnostic(ErrorCode.ERR_BaseInBadContext, "base").WithLocation(19, 34) ); } [Fact] public void TestWithAccessModifiers_Private() { string source = @" public class C { public string Property { get { throw null; } private init { throw null; } } void M() { _ = new C() { Property = null }; Property = null; // 1 } C() { Property = null; } } public class Other { void M(C c) { _ = new C() { Property = null }; // 2, 3 c.Property = null; // 4 } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9), // (20,17): error CS0122: 'C.C()' is inaccessible due to its protection level // _ = new C() { Property = null }; // 2, 3 Diagnostic(ErrorCode.ERR_BadAccess, "C").WithArguments("C.C()").WithLocation(20, 17), // (20,23): error CS0272: The property or indexer 'C.Property' cannot be used in this context because the set accessor is inaccessible // _ = new C() { Property = null }; // 2, 3 Diagnostic(ErrorCode.ERR_InaccessibleSetter, "Property").WithArguments("C.Property").WithLocation(20, 23), // (21,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(21, 9) ); } [Fact] public void TestWithAccessModifiers_Protected() { string source = @" public class C { public string Property { get { throw null; } protected init { throw null; } } void M() { _ = new C() { Property = null }; Property = null; // 1 } public C() { Property = null; } } public class Derived : C { void M(C c) { _ = new C() { Property = null }; // 2 c.Property = null; // 3, 4 Property = null; // 5 } Derived() { _ = new C() { Property = null }; // 6 _ = new Derived() { Property = null }; Property = null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9), // (20,23): error CS1540: Cannot access protected member 'C.Property' via a qualifier of type 'C'; the qualifier must be of type 'Derived' (or derived from it) // _ = new C() { Property = null }; // 2 Diagnostic(ErrorCode.ERR_BadProtectedAccess, "Property").WithArguments("C.Property", "C", "Derived").WithLocation(20, 23), // (21,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 3, 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(21, 9), // (22,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 5 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(22, 9), // (27,23): error CS1540: Cannot access protected member 'C.Property' via a qualifier of type 'C'; the qualifier must be of type 'Derived' (or derived from it) // _ = new C() { Property = null }; // 6 Diagnostic(ErrorCode.ERR_BadProtectedAccess, "Property").WithArguments("C.Property", "C", "Derived").WithLocation(27, 23) ); } [Fact] public void TestWithAccessModifiers_Protected_WithoutGetter() { string source = @" public class C { public string Property { protected init { throw null; } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,19): error CS0276: 'C.Property': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // public string Property { protected init { throw null; } } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "Property").WithArguments("C.Property").WithLocation(4, 19) ); } [Fact] public void OverrideScenarioWithSubstitutions() { string source = @" public class C<T> { public string Property { get; init; } } public class Derived : C<string> { void M() { Property = null; // 1 } Derived() { Property = null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (10,9): error CS8802: Init-only property or indexer 'C<string>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<string>.Property").WithLocation(10, 9) ); var property = (PropertySymbol)comp.GlobalNamespace.GetTypeMember("Derived").BaseTypeNoUseSiteDiagnostics.GetMember("Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().GetMethod.IsInitOnly); Assert.True(property.SetMethod.IsInitOnly); Assert.True(property.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void ImplementationScenarioWithSubstitutions() { string source = @" public interface I<T> { public string Property { get; init; } } public class CWithInit : I<string> { public string Property { get; init; } } public class CWithoutInit : I<string> // 1 { public string Property { get; set; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (10,29): error CS8804: 'CWithoutInit' does not implement interface member 'I<string>.Property.init'. 'CWithoutInit.Property.set' cannot implement 'I<string>.Property.init'. // public class CWithoutInit : I<string> // 1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I<string>").WithArguments("CWithoutInit", "I<string>.Property.init", "CWithoutInit.Property.set").WithLocation(10, 29) ); var property = (PropertySymbol)comp.GlobalNamespace.GetMember("I.Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().GetMethod.IsInitOnly); Assert.True(property.SetMethod.IsInitOnly); Assert.True(property.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void InLambdaOrLocalFunction_InMethodOrDerivedConstructor() { string source = @" public class C<T> { public string Property { get; init; } } public class Derived : C<string> { void M() { System.Action a = () => { Property = null; // 1 }; local(); void local() { Property = null; // 2 } } Derived() { System.Action a = () => { Property = null; // 3 }; local(); void local() { Property = null; // 4 } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (12,13): error CS8802: Init-only property or indexer 'C<string>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<string>.Property").WithLocation(12, 13), // (18,13): error CS8802: Init-only property or indexer 'C<string>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<string>.Property").WithLocation(18, 13), // (26,13): error CS8802: Init-only property or indexer 'C<string>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<string>.Property").WithLocation(26, 13), // (32,13): error CS8802: Init-only property or indexer 'C<string>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<string>.Property").WithLocation(32, 13) ); } [Fact] public void InLambdaOrLocalFunction_InConstructorOrInit() { string source = @" public class C<T> { public string Property { get; init; } C() { System.Action a = () => { Property = null; // 1 }; local(); void local() { Property = null; // 2 } } public string Other { init { System.Action a = () => { Property = null; // 3 }; local(); void local() { Property = null; // 4 } } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (10,13): error CS8802: Init-only property or indexer 'C<T>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<T>.Property").WithLocation(10, 13), // (16,13): error CS8802: Init-only property or indexer 'C<T>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<T>.Property").WithLocation(16, 13), // (26,17): error CS8802: Init-only property or indexer 'C<T>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<T>.Property").WithLocation(26, 17), // (32,17): error CS8802: Init-only property or indexer 'C<T>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<T>.Property").WithLocation(32, 17) ); } [Fact] public void MissingIsInitOnlyType_Property() { string source = @" public class C { public string Property { get => throw null; init { } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,49): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported // public string Property { get => throw null; init { } } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit").WithLocation(4, 49) ); } [Fact] public void InitOnlyPropertyAssignmentDisallowed() { string source = @" public class C { public string Property { get; init; } void M() { Property = null; // 1 _ = new C() { Property = null }; } public C() { Property = null; } public string InitOnlyProperty { get { Property = null; // 2 return null; } init { Property = null; } } public string RegularProperty { get { Property = null; // 3 return null; } set { Property = null; // 4 } } public string otherField = (Property = null); // 5 } class Derived : C { } class Derived2 : Derived { void M() { Property = null; // 6 } Derived2() { Property = null; } public string InitOnlyProperty2 { get { Property = null; // 7 return null; } init { Property = null; } } public string RegularProperty2 { get { Property = null; // 8 return null; } set { Property = null; // 9 } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9), // (21,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(21, 13), // (34,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(34, 13), // (39,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(39, 13), // (43,33): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.Property' // public string otherField = (Property = null); // 5 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "Property").WithArguments("C.Property").WithLocation(43, 33), // (54,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 6 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(54, 9), // (66,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 7 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(66, 13), // (79,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 8 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(79, 13), // (84,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 9 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(84, 13) ); var property = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().GetMethod.IsInitOnly); Assert.True(property.SetMethod.IsInitOnly); Assert.True(property.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void InitOnlyPropertyAssignmentAllowedInWithInitializer() { string source = @" record C { public int Property { get; init; } void M(C c) { _ = c with { Property = 1 }; } } record Derived : C { } record Derived2 : Derived { void M(C c) { _ = c with { Property = 1 }; _ = this with { Property = 1 }; } } class Other { void M() { var c = new C() with { Property = 42 }; System.Console.Write($""{c.Property}""); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void InitOnlyPropertyAssignmentAllowedInWithInitializer_Evaluation() { string source = @" record C { private int field; public int Property { get { return field; } init { field = value; System.Console.Write(""set ""); } } public C Clone() { System.Console.Write(""clone ""); return this; } } class Other { public static void Main() { var c = new C() with { Property = 42 }; System.Console.Write($""{c.Property}""); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "clone set 42"); } [Fact] public void EvaluationInitOnlySetter() { string source = @" public class C { public int Property { init { System.Console.Write(value + "" ""); } } public int Property2 { init { System.Console.Write(value); } } C() { System.Console.Write(""Main ""); } static void Main() { _ = new C() { Property = 42, Property2 = 43}; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Main 42 43"); } [Theory] [InlineData(true)] [InlineData(false)] public void EvaluationInitOnlySetter_OverrideAutoProp(bool emitImage) { string parent = @" public class Base { public virtual int Property { get; init; } }"; string source = @" public class C : Base { int field; public override int Property { get { System.Console.Write(""get:"" + field + "" ""); return field; } init { field = value; System.Console.Write(""set:"" + value + "" ""); } } public C() { System.Console.Write(""Main ""); } }"; string main = @" public class D { static void Main() { var c = new C() { Property = 42 }; _ = c.Property; } } "; var libComp = CreateCompilation(new[] { parent, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); var comp = CreateCompilation(new[] { source, main }, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "Main set:42 get:42"); libComp = CreateCompilation(new[] { parent, source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp = CreateCompilation(new[] { main }, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "Main set:42 get:42"); } [Theory] [InlineData(true)] [InlineData(false)] public void EvaluationInitOnlySetter_AutoProp(bool emitImage) { string source = @" public class C { public int Property { get; init; } public C() { System.Console.Write(""Main ""); } }"; string main = @" public class D { static void Main() { var c = new C() { Property = 42 }; System.Console.Write($""{c.Property}""); } } "; var libComp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); var comp = CreateCompilation(new[] { main }, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "Main 42"); } [Theory] [InlineData(true)] [InlineData(false)] public void EvaluationInitOnlySetter_Implementation(bool emitImage) { string parent = @" public interface I { int Property { get; init; } }"; string source = @" public class C : I { int field; public int Property { get { System.Console.Write(""get:"" + field + "" ""); return field; } init { field = value; System.Console.Write(""set:"" + value + "" ""); } } public C() { System.Console.Write(""Main ""); } }"; string main = @" public class D { static void Main() { M<C>(); } static void M<T>() where T : I, new() { var t = new T() { Property = 42 }; _ = t.Property; } } "; var libComp = CreateCompilation(new[] { parent, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); var comp = CreateCompilation(new[] { source, main }, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "Main set:42 get:42"); libComp = CreateCompilation(new[] { parent, source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp = CreateCompilation(new[] { main }, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "Main set:42 get:42"); } [Fact] public void DisallowedOnStaticMembers() { string source = @" public class C { public static string Property { get; init; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,42): error CS8806: The 'init' accessor is not valid on static members // public static string Property { get; init; } Diagnostic(ErrorCode.ERR_BadInitAccessor, "init").WithLocation(4, 42) ); var property = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().GetMethod.IsInitOnly); Assert.False(property.SetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void DisallowedOnOtherInstances() { string source = @" public class C { public string Property { get; init; } public C c; public C() { c.Property = null; // 1 } public string InitOnlyProperty { init { c.Property = null; // 2 } } } public class Derived : C { Derived() { c.Property = null; // 3 } public string InitOnlyProperty2 { init { c.Property = null; // 4 } } } public class Caller { void M(C c) { _ = new C() { Property = (c.Property = null) // 5 }; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (9,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(9, 9), // (16,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(16, 13), // (24,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(24, 9), // (31,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(31, 13), // (41,18): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // (c.Property = null) // 5 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(41, 18) ); } [Fact] public void DeconstructionAssignmentDisallowed() { string source = @" public class C { public string Property { get; init; } void M() { (Property, (Property, Property)) = (null, (null, null)); // 1, 2, 3 } C() { (Property, (Property, Property)) = (null, (null, null)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,10): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // (Property, (Property, Property)) = (null, (null, null)); // 1, 2, 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 10), // (8,21): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // (Property, (Property, Property)) = (null, (null, null)); // 1, 2, 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 21), // (8,31): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // (Property, (Property, Property)) = (null, (null, null)); // 1, 2, 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 31) ); } [Fact] public void OutParameterAssignmentDisallowed() { string source = @" public class C { public string Property { get; init; } void M() { M2(out Property); // 1 } void M2(out string s) => throw null; } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,16): error CS0206: A property or indexer may not be passed as an out or ref parameter // M2(out Property); // 1 Diagnostic(ErrorCode.ERR_RefProperty, "Property").WithArguments("C.Property").WithLocation(8, 16) ); } [Fact] public void CompoundAssignmentDisallowed() { string source = @" public class C { public int Property { get; init; } void M() { Property += 42; // 1 } C() { Property += 42; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property += 42; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9) ); } [Fact] public void CompoundAssignmentDisallowed_OrAssignment() { string source = @" public class C { public bool Property { get; init; } void M() { Property |= true; // 1 } C() { Property |= true; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property |= true; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9) ); } [Fact] public void CompoundAssignmentDisallowed_NullCoalescingAssignment() { string source = @" public class C { public string Property { get; init; } void M() { Property ??= null; // 1 } C() { Property ??= null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property ??= null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9) ); } [Fact] public void CompoundAssignmentDisallowed_Increment() { string source = @" public class C { public int Property { get; init; } void M() { Property++; // 1 } C() { Property++; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property++; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9) ); } [Fact] public void RefProperty() { string source = @" public class C { ref int Property1 { get; init; } ref int Property2 { init; } ref int Property3 { get => throw null; init => throw null; } ref int Property4 { init => throw null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,13): error CS8145: Auto-implemented properties cannot return by reference // ref int Property1 { get; init; } Diagnostic(ErrorCode.ERR_AutoPropertyCannotBeRefReturning, "Property1").WithArguments("C.Property1").WithLocation(4, 13), // (4,30): error CS8147: Properties which return by reference cannot have set accessors // ref int Property1 { get; init; } Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "init").WithArguments("C.Property1.init").WithLocation(4, 30), // (5,13): error CS8146: Properties which return by reference must have a get accessor // ref int Property2 { init; } Diagnostic(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, "Property2").WithArguments("C.Property2").WithLocation(5, 13), // (6,44): error CS8147: Properties which return by reference cannot have set accessors // ref int Property3 { get => throw null; init => throw null; } Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "init").WithArguments("C.Property3.init").WithLocation(6, 44), // (7,13): error CS8146: Properties which return by reference must have a get accessor // ref int Property4 { init => throw null; } Diagnostic(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, "Property4").WithArguments("C.Property4").WithLocation(7, 13) ); } [Fact] public void VerifyPESymbols_Property() { string source = @" public class C { public string Property { get; init; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); // PE verification fails: [ : C::set_Property] Cannot change initonly field outside its .ctor. CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var c = (NamedTypeSymbol)m.GlobalNamespace.GetMember("C"); var property = (PropertySymbol)c.GetMembers("Property").Single(); Assert.Equal("System.String C.Property { get; init; }", property.ToTestDisplayString()); Assert.Equal(0, property.CustomModifierCount()); var propertyAttributes = property.GetAttributes().Select(a => a.ToString()); AssertEx.Empty(propertyAttributes); var getter = property.GetMethod; Assert.Empty(property.GetMethod.ReturnTypeWithAnnotations.CustomModifiers); Assert.False(getter.IsInitOnly); Assert.False(getter.GetPublicSymbol().IsInitOnly); var getterAttributes = getter.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(getterAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute" }, getterAttributes); } var setter = property.SetMethod; Assert.True(setter.IsInitOnly); Assert.True(setter.GetPublicSymbol().IsInitOnly); var setterAttributes = property.SetMethod.GetAttributes().Select(a => a.ToString()); var modifier = property.SetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single(); Assert.Equal("System.Runtime.CompilerServices.IsExternalInit", modifier.Modifier.ToTestDisplayString()); Assert.False(modifier.IsOptional); if (isSource) { AssertEx.Empty(setterAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute" }, setterAttributes); } var backingField = (FieldSymbol)c.GetMembers("<Property>k__BackingField").Single(); var backingFieldAttributes = backingField.GetAttributes().Select(a => a.ToString()); Assert.True(backingField.IsReadOnly); if (isSource) { AssertEx.Empty(backingFieldAttributes); } else { AssertEx.Equal( new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute", "System.Diagnostics.DebuggerBrowsableAttribute(System.Diagnostics.DebuggerBrowsableState.Never)" }, backingFieldAttributes); var peBackingField = (PEFieldSymbol)backingField; Assert.Equal(System.Reflection.FieldAttributes.InitOnly | System.Reflection.FieldAttributes.Private, peBackingField.Flags); } } } [Theory] [InlineData(true)] [InlineData(false)] public void AssignmentDisallowed_PE(bool emitImage) { string lib_cs = @" public class C { public string Property { get; init; } } "; var libComp = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); libComp.VerifyDiagnostics(); string source = @" public class Other { public C c; void M() { c.Property = null; // 1 } public Other() { c.Property = null; // 2 } public string InitOnlyProperty { get { c.Property = null; // 3 return null; } init { c.Property = null; // 4 } } public string RegularProperty { get { c.Property = null; // 5 return null; } set { c.Property = null; // 6 } } } class Derived : C { } class Derived2 : Derived { void M() { Property = null; // 7 base.Property = null; // 8 } Derived2() { Property = null; base.Property = null; } public string InitOnlyProperty2 { get { Property = null; // 9 base.Property = null; // 10 return null; } init { Property = null; base.Property = null; } } public string RegularProperty2 { get { Property = null; // 11 base.Property = null; // 12 return null; } set { Property = null; // 13 base.Property = null; // 14 } } } "; var comp = CreateCompilation(source, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(8, 9), // (13,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(13, 9), // (20,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(20, 13), // (25,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(25, 13), // (33,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 5 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(33, 13), // (38,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 6 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(38, 13), // (51,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 7 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(51, 9), // (52,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // base.Property = null; // 8 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "base.Property").WithArguments("C.Property").WithLocation(52, 9), // (65,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 9 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(65, 13), // (66,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // base.Property = null; // 10 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "base.Property").WithArguments("C.Property").WithLocation(66, 13), // (80,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 11 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(80, 13), // (81,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // base.Property = null; // 12 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "base.Property").WithArguments("C.Property").WithLocation(81, 13), // (86,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 13 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(86, 13), // (87,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // base.Property = null; // 14 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "base.Property").WithArguments("C.Property").WithLocation(87, 13) ); } [Fact, WorkItem(50053, "https://github.com/dotnet/roslyn/issues/50053")] public void PrivatelyImplementingInitOnlyProperty_ReferenceConversion() { string source = @" var x = new DerivedType() { SomethingElse = 42 }; System.Console.Write(x.SomethingElse); public interface ISomething { int Property { get; init; } } public record BaseType : ISomething { int ISomething.Property { get; init; } } public record DerivedType : BaseType { public int SomethingElse { get => ((ISomething)this).Property; init => ((ISomething)this).Property = value; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (13,17): error CS8852: Init-only property or indexer 'ISomething.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // init => ((ISomething)this).Property = value; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "((ISomething)this).Property").WithArguments("ISomething.Property").WithLocation(13, 17) ); } [Fact, WorkItem(50053, "https://github.com/dotnet/roslyn/issues/50053")] public void PrivatelyImplementingInitOnlyProperty_BoxingConversion() { string source = @" var x = new Type() { SomethingElse = 42 }; public interface ISomething { int Property { get; init; } } public struct Type : ISomething { int ISomething.Property { get; init; } public int SomethingElse { get => throw null; init => ((ISomething)this).Property = value; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (13,17): error CS8852: Init-only property or indexer 'ISomething.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // init => ((ISomething)this).Property = value; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "((ISomething)this).Property").WithArguments("ISomething.Property").WithLocation(13, 17) ); } [Fact] public void OverridingInitOnlyProperty() { string source = @" public class Base { public virtual string Property { get; init; } } public class DerivedWithInit : Base { public override string Property { get; init; } } public class DerivedWithoutInit : Base { public override string Property { get; set; } // 1 } public class DerivedWithInitSetterOnly : Base { public override string Property { init { } } } public class DerivedWithoutInitSetterOnly : Base { public override string Property { set { } } // 2 } public class DerivedGetterOnly : Base { public override string Property { get => null; } } public class DerivedDerivedWithInit : DerivedGetterOnly { public override string Property { init { } } } public class DerivedDerivedWithoutInit : DerivedGetterOnly { public override string Property { set { } } // 3 } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (13,28): error CS8803: 'DerivedWithoutInit.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { get; set; } // 1 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithoutInit.Property", "Base.Property").WithLocation(13, 28), // (22,28): error CS8803: 'DerivedWithoutInitSetterOnly.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { set { } } // 2 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithoutInitSetterOnly.Property", "Base.Property").WithLocation(22, 28), // (35,28): error CS8803: 'DerivedDerivedWithoutInit.Property' must match by init-only of overridden member 'DerivedGetterOnly.Property' // public override string Property { set { } } // 3 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedDerivedWithoutInit.Property", "DerivedGetterOnly.Property").WithLocation(35, 28) ); } [Theory] [InlineData(true)] [InlineData(false)] public void OverridingInitOnlyProperty_Metadata(bool emitAsImage) { string lib_cs = @" public class Base { public virtual string Property { get; init; } }"; var libComp = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); libComp.VerifyDiagnostics(); string source = @" public class DerivedWithInit : Base { public override string Property { get; init; } } public class DerivedWithoutInit : Base { public override string Property { get; set; } // 1 } public class DerivedWithInitSetterOnly : Base { public override string Property { init { } } } public class DerivedWithoutInitSetterOnly : Base { public override string Property { set { } } // 2 } public class DerivedGetterOnly : Base { public override string Property { get => null; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { emitAsImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (8,28): error CS8803: 'DerivedWithoutInit.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { get; set; } // 1 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithoutInit.Property", "Base.Property").WithLocation(8, 28), // (16,28): error CS8803: 'DerivedWithoutInitSetterOnly.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { set { } } // 2 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithoutInitSetterOnly.Property", "Base.Property").WithLocation(16, 28) ); } [Fact] public void OverridingRegularProperty() { string source = @" public class Base { public virtual string Property { get; set; } } public class DerivedWithInit : Base { public override string Property { get; init; } // 1 } public class DerivedWithoutInit : Base { public override string Property { get; set; } } public class DerivedWithInitSetterOnly : Base { public override string Property { init { } } // 2 } public class DerivedWithoutInitSetterOnly : Base { public override string Property { set { } } } public class DerivedGetterOnly : Base { public override string Property { get => null; } } public class DerivedDerivedWithInit : DerivedGetterOnly { public override string Property { init { } } // 3 } public class DerivedDerivedWithoutInit : DerivedGetterOnly { public override string Property { set { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (9,28): error CS8803: 'DerivedWithInit.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { get; init; } // 1 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithInit.Property", "Base.Property").WithLocation(9, 28), // (18,28): error CS8803: 'DerivedWithInitSetterOnly.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { init { } } // 2 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithInitSetterOnly.Property", "Base.Property").WithLocation(18, 28), // (31,28): error CS8803: 'DerivedDerivedWithInit.Property' must match by init-only of overridden member 'DerivedGetterOnly.Property' // public override string Property { init { } } // 3 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedDerivedWithInit.Property", "DerivedGetterOnly.Property").WithLocation(31, 28) ); } [Fact] public void OverridingGetterOnlyProperty() { string source = @" public class Base { public virtual string Property { get => null; } } public class DerivedWithInit : Base { public override string Property { get; init; } // 1 } public class DerivedWithoutInit : Base { public override string Property { get; set; } // 2 } public class DerivedWithInitSetterOnly : Base { public override string Property { init { } } // 3 } public class DerivedWithoutInitSetterOnly : Base { public override string Property { set { } } // 4 } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,44): error CS0546: 'DerivedWithInit.Property.init': cannot override because 'Base.Property' does not have an overridable set accessor // public override string Property { get; init; } // 1 Diagnostic(ErrorCode.ERR_NoSetToOverride, "init").WithArguments("DerivedWithInit.Property.init", "Base.Property").WithLocation(8, 44), // (12,44): error CS0546: 'DerivedWithoutInit.Property.set': cannot override because 'Base.Property' does not have an overridable set accessor // public override string Property { get; set; } // 2 Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("DerivedWithoutInit.Property.set", "Base.Property").WithLocation(12, 44), // (16,39): error CS0546: 'DerivedWithInitSetterOnly.Property.init': cannot override because 'Base.Property' does not have an overridable set accessor // public override string Property { init { } } // 3 Diagnostic(ErrorCode.ERR_NoSetToOverride, "init").WithArguments("DerivedWithInitSetterOnly.Property.init", "Base.Property").WithLocation(16, 39), // (20,39): error CS0546: 'DerivedWithoutInitSetterOnly.Property.set': cannot override because 'Base.Property' does not have an overridable set accessor // public override string Property { set { } } // 4 Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("DerivedWithoutInitSetterOnly.Property.set", "Base.Property").WithLocation(20, 39) ); } [Fact] public void OverridingSetterOnlyProperty() { string source = @" public class Base { public virtual string Property { set { } } } public class DerivedWithInit : Base { public override string Property { get; init; } // 1, 2 } public class DerivedWithoutInit : Base { public override string Property { get; set; } // 3 } public class DerivedWithInitSetterOnly : Base { public override string Property { init { } } // 4 } public class DerivedWithoutInitGetterOnly : Base { public override string Property { get => null; } // 5 } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,28): error CS8803: 'DerivedWithInit.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { get; init; } // 1, 2 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithInit.Property", "Base.Property").WithLocation(8, 28), // (8,39): error CS0545: 'DerivedWithInit.Property.get': cannot override because 'Base.Property' does not have an overridable get accessor // public override string Property { get; init; } // 1, 2 Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("DerivedWithInit.Property.get", "Base.Property").WithLocation(8, 39), // (12,39): error CS0545: 'DerivedWithoutInit.Property.get': cannot override because 'Base.Property' does not have an overridable get accessor // public override string Property { get; set; } // 3 Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("DerivedWithoutInit.Property.get", "Base.Property").WithLocation(12, 39), // (16,28): error CS8803: 'DerivedWithInitSetterOnly.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { init { } } // 4 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithInitSetterOnly.Property", "Base.Property").WithLocation(16, 28), // (20,39): error CS0545: 'DerivedWithoutInitGetterOnly.Property.get': cannot override because 'Base.Property' does not have an overridable get accessor // public override string Property { get => null; } // 5 Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("DerivedWithoutInitGetterOnly.Property.get", "Base.Property").WithLocation(20, 39) ); } [Fact] public void ImplementingInitOnlyProperty() { string source = @" public interface I { string Property { get; init; } } public class DerivedWithInit : I { public string Property { get; init; } } public class DerivedWithoutInit : I // 1 { public string Property { get; set; } } public class DerivedWithInitSetterOnly : I // 2 { public string Property { init { } } } public class DerivedWithoutInitGetterOnly : I // 3 { public string Property { get => null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (10,35): error CS8804: 'DerivedWithoutInit' does not implement interface member 'I.Property.init'. 'DerivedWithoutInit.Property.set' cannot implement 'I.Property.init'. // public class DerivedWithoutInit : I // 1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("DerivedWithoutInit", "I.Property.init", "DerivedWithoutInit.Property.set").WithLocation(10, 35), // (14,42): error CS0535: 'DerivedWithInitSetterOnly' does not implement interface member 'I.Property.get' // public class DerivedWithInitSetterOnly : I // 2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("DerivedWithInitSetterOnly", "I.Property.get").WithLocation(14, 42), // (18,45): error CS0535: 'DerivedWithoutInitGetterOnly' does not implement interface member 'I.Property.init' // public class DerivedWithoutInitGetterOnly : I // 3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("DerivedWithoutInitGetterOnly", "I.Property.init").WithLocation(18, 45) ); } [Fact] public void ImplementingSetterOnlyProperty() { string source = @" public interface I { string Property { set; } } public class DerivedWithInit : I // 1 { public string Property { get; init; } } public class DerivedWithoutInit : I { public string Property { get; set; } } public class DerivedWithInitSetterOnly : I // 2 { public string Property { init { } } } public class DerivedWithoutInitGetterOnly : I // 3 { public string Property { get => null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,32): error CS8804: 'DerivedWithInit' does not implement interface member 'I.Property.set'. 'DerivedWithInit.Property.init' cannot implement 'I.Property.set'. // public class DerivedWithInit : I // 1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("DerivedWithInit", "I.Property.set", "DerivedWithInit.Property.init").WithLocation(6, 32), // (14,42): error CS8804: 'DerivedWithInitSetterOnly' does not implement interface member 'I.Property.set'. 'DerivedWithInitSetterOnly.Property.init' cannot implement 'I.Property.set'. // public class DerivedWithInitSetterOnly : I // 2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("DerivedWithInitSetterOnly", "I.Property.set", "DerivedWithInitSetterOnly.Property.init").WithLocation(14, 42), // (18,45): error CS0535: 'DerivedWithoutInitGetterOnly' does not implement interface member 'I.Property.set' // public class DerivedWithoutInitGetterOnly : I // 3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("DerivedWithoutInitGetterOnly", "I.Property.set").WithLocation(18, 45) ); } [Fact] public void ObjectCreationOnInterface() { string source = @" public interface I { string Property { set; } string InitProperty { init; } } public class C { void M<T>() where T: I, new() { _ = new T() { Property = null, InitProperty = null }; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void HidingInitOnlySetterOnlyProperty() { string source = @" public class Base { public string Property { init { } } } public class Derived : Base { public string Property { init { } } // 1 } public class DerivedWithNew : Base { public new string Property { init { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,19): warning CS0108: 'Derived.Property' hides inherited member 'Base.Property'. Use the new keyword if hiding was intended. // public string Property { init { } } // 1 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("Derived.Property", "Base.Property").WithLocation(8, 19) ); } [Theory] [InlineData(true)] [InlineData(false)] public void ImplementingSetterOnlyProperty_Metadata(bool emitAsImage) { string lib_cs = @" public interface I { string Property { set; } }"; var libComp = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); libComp.VerifyEmitDiagnostics(); string source = @" public class DerivedWithInit : I // 1 { public string Property { get; init; } } public class DerivedWithoutInit : I { public string Property { get; set; } } public class DerivedWithInitSetterOnly : I // 2 { public string Property { init { } } } public class DerivedWithoutInitGetterOnly : I // 3 { public string Property { get => null; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { emitAsImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (2,32): error CS8804: 'DerivedWithInit' does not implement interface member 'I.Property.set'. 'DerivedWithInit.Property.init' cannot implement 'I.Property.set'. // public class DerivedWithInit : I // 1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("DerivedWithInit", "I.Property.set", "DerivedWithInit.Property.init").WithLocation(2, 32), // (10,42): error CS8804: 'DerivedWithInitSetterOnly' does not implement interface member 'I.Property.set'. 'DerivedWithInitSetterOnly.Property.init' cannot implement 'I.Property.set'. // public class DerivedWithInitSetterOnly : I // 2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("DerivedWithInitSetterOnly", "I.Property.set", "DerivedWithInitSetterOnly.Property.init").WithLocation(10, 42), // (14,45): error CS0535: 'DerivedWithoutInitGetterOnly' does not implement interface member 'I.Property.set' // public class DerivedWithoutInitGetterOnly : I // 3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("DerivedWithoutInitGetterOnly", "I.Property.set").WithLocation(14, 45) ); } [Fact] public void ImplementingSetterOnlyProperty_Explicitly() { string source = @" public interface I { string Property { set; } } public class DerivedWithInit : I { string I.Property { init { } } // 1 } public class DerivedWithInitAndGetter : I { string I.Property { get; init; } // 2, 3 } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,25): error CS8805: Accessors 'DerivedWithInit.I.Property.init' and 'I.Property.set' should both be init-only or neither // string I.Property { init { } } // 1 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "init").WithArguments("DerivedWithInit.I.Property.init", "I.Property.set").WithLocation(8, 25), // (12,25): error CS0550: 'DerivedWithInitAndGetter.I.Property.get' adds an accessor not found in interface member 'I.Property' // string I.Property { get; init; } // 2, 3 Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("DerivedWithInitAndGetter.I.Property.get", "I.Property").WithLocation(12, 25), // (12,30): error CS8805: Accessors 'DerivedWithInitAndGetter.I.Property.init' and 'I.Property.set' should both be init-only or neither // string I.Property { get; init; } // 2, 3 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "init").WithArguments("DerivedWithInitAndGetter.I.Property.init", "I.Property.set").WithLocation(12, 30) ); } [Fact] public void ImplementingSetterOnlyInitOnlyProperty_Explicitly() { string source = @" public interface I { string Property { init; } } public class DerivedWithoutInit : I { string I.Property { set { } } // 1 } public class DerivedWithInit : I { string I.Property { init { } } } public class DerivedWithInitAndGetter : I { string I.Property { get; init; } // 2 } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,25): error CS8805: Accessors 'DerivedWithoutInit.I.Property.set' and 'I.Property.init' should both be init-only or neither // string I.Property { set { } } // 1 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "set").WithArguments("DerivedWithoutInit.I.Property.set", "I.Property.init").WithLocation(8, 25), // (16,25): error CS0550: 'DerivedWithInitAndGetter.I.Property.get' adds an accessor not found in interface member 'I.Property' // string I.Property { get; init; } // 2 Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("DerivedWithInitAndGetter.I.Property.get", "I.Property").WithLocation(16, 25) ); } [Theory] [InlineData(true)] [InlineData(false)] public void ImplementingSetterOnlyInitOnlyProperty_Metadata_Explicitly(bool emitAsImage) { string lib_cs = @" public interface I { string Property { init; } }"; var libComp = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); libComp.VerifyDiagnostics(); string source = @" public class DerivedWithoutInit : I { string I.Property { set { } } // 1 } public class DerivedWithInit : I { string I.Property { init { } } } public class DerivedGetterOnly : I // 2 { string I.Property { get => null; } // 3, 4 } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { emitAsImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (4,25): error CS8805: Accessors 'DerivedWithoutInit.I.Property.set' and 'I.Property.init' should both be init-only or neither // string I.Property { set { } } // 1 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "set").WithArguments("DerivedWithoutInit.I.Property.set", "I.Property.init").WithLocation(4, 25), // (10,34): error CS0535: 'DerivedGetterOnly' does not implement interface member 'I.Property.init' // public class DerivedGetterOnly : I // 2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("DerivedGetterOnly", "I.Property.init").WithLocation(10, 34), // (12,14): error CS0551: Explicit interface implementation 'DerivedGetterOnly.I.Property' is missing accessor 'I.Property.init' // string I.Property { get => null; } // 3, 4 Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "Property").WithArguments("DerivedGetterOnly.I.Property", "I.Property.init").WithLocation(12, 14), // (12,25): error CS0550: 'DerivedGetterOnly.I.Property.get' adds an accessor not found in interface member 'I.Property' // string I.Property { get => null; } // 3, 4 Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("DerivedGetterOnly.I.Property.get", "I.Property").WithLocation(12, 25) ); } [Fact] public void DIM_TwoInitOnlySetters() { string source = @" public interface I1 { string Property { init; } } public interface I2 { string Property { init; } } public interface IWithoutInit : I1, I2 { string Property { set; } // 1 } public interface IWithInit : I1, I2 { string Property { init; } // 2 } public interface IWithInitWithNew : I1, I2 { new string Property { init; } } public interface IWithInitWithDefaultImplementation : I1, I2 { string Property { init { } } // 3 } public interface IWithInitWithExplicitImplementation : I1, I2 { string I1.Property { init { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular9); Assert.True(comp.Assembly.RuntimeSupportsDefaultInterfaceImplementation); comp.VerifyEmitDiagnostics( // (12,12): warning CS0108: 'IWithoutInit.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { set; } // 1 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithoutInit.Property", "I1.Property").WithLocation(12, 12), // (16,12): warning CS0108: 'IWithInit.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { init; } // 2 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithInit.Property", "I1.Property").WithLocation(16, 12), // (24,12): warning CS0108: 'IWithInitWithDefaultImplementation.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { init { } } // 3 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithInitWithDefaultImplementation.Property", "I1.Property").WithLocation(24, 12) ); } [Fact] public void DIM_OneInitOnlySetter() { string source = @" public interface I1 { string Property { init; } } public interface I2 { string Property { set; } } public interface IWithoutInit : I1, I2 { string Property { set; } // 1 } public interface IWithInit : I1, I2 { string Property { init; } // 2 } public interface IWithInitWithNew : I1, I2 { new string Property { init; } } public interface IWithoutInitWithNew : I1, I2 { new string Property { set; } } public interface IWithInitWithImplementation : I1, I2 { string Property { init { } } // 3 } public interface IWithInitWithExplicitImplementationOfI1 : I1, I2 { string I1.Property { init { } } } public interface IWithInitWithExplicitImplementationOfI2 : I1, I2 { string I2.Property { init { } } // 4 } public interface IWithoutInitWithExplicitImplementationOfI1 : I1, I2 { string I1.Property { set { } } // 5 } public interface IWithoutInitWithExplicitImplementationOfI2 : I1, I2 { string I2.Property { set { } } } public interface IWithoutInitWithExplicitImplementationOfBoth : I1, I2 { string I1.Property { init { } } string I2.Property { set { } } } public class CWithExplicitImplementation : I1, I2 { string I1.Property { init { } } string I2.Property { set { } } } public class CWithImplementationWithInitOnly : I1, I2 // 6 { public string Property { init { } } } public class CWithImplementationWithoutInitOnly : I1, I2 // 7 { public string Property { set { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular9); Assert.True(comp.Assembly.RuntimeSupportsDefaultInterfaceImplementation); comp.VerifyEmitDiagnostics( // (13,12): warning CS0108: 'IWithoutInit.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { set; } // 1 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithoutInit.Property", "I1.Property").WithLocation(13, 12), // (17,12): warning CS0108: 'IWithInit.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { init; } // 2 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithInit.Property", "I1.Property").WithLocation(17, 12), // (31,12): warning CS0108: 'IWithInitWithImplementation.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { init { } } // 3 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithInitWithImplementation.Property", "I1.Property").WithLocation(31, 12), // (40,26): error CS8805: Accessors 'IWithInitWithExplicitImplementationOfI2.I2.Property.init' and 'I2.Property.set' should both be init-only or neither // string I2.Property { init { } } // 4 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "init").WithArguments("IWithInitWithExplicitImplementationOfI2.I2.Property.init", "I2.Property.set").WithLocation(40, 26), // (45,26): error CS8805: Accessors 'IWithoutInitWithExplicitImplementationOfI1.I1.Property.set' and 'I1.Property.init' should both be init-only or neither // string I1.Property { set { } } // 5 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "set").WithArguments("IWithoutInitWithExplicitImplementationOfI1.I1.Property.set", "I1.Property.init").WithLocation(45, 26), // (62,52): error CS8804: 'CWithImplementationWithInitOnly' does not implement interface member 'I2.Property.set'. 'CWithImplementationWithInitOnly.Property.init' cannot implement 'I2.Property.set'. // public class CWithImplementationWithInitOnly : I1, I2 // 6 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I2").WithArguments("CWithImplementationWithInitOnly", "I2.Property.set", "CWithImplementationWithInitOnly.Property.init").WithLocation(62, 52), // (66,51): error CS8804: 'CWithImplementationWithoutInitOnly' does not implement interface member 'I1.Property.init'. 'CWithImplementationWithoutInitOnly.Property.set' cannot implement 'I1.Property.init'. // public class CWithImplementationWithoutInitOnly : I1, I2 // 7 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I1").WithArguments("CWithImplementationWithoutInitOnly", "I1.Property.init", "CWithImplementationWithoutInitOnly.Property.set").WithLocation(66, 51) ); } [Fact] public void EventWithInitOnly() { string source = @" public class C { public event System.Action Event { init { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,32): error CS0065: 'C.Event': event property must have both add and remove accessors // public event System.Action Event Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "Event").WithArguments("C.Event").WithLocation(4, 32), // (6,9): error CS1055: An add or remove accessor expected // init { } Diagnostic(ErrorCode.ERR_AddOrRemoveExpected, "init").WithLocation(6, 9) ); var members = ((NamedTypeSymbol)comp.GlobalNamespace.GetMember("C")).GetMembers(); AssertEx.SetEqual(members.ToTestDisplayStrings(), new[] { "event System.Action C.Event", "C..ctor()" }); } [Fact] public void EventAccessorsAreNotInitOnly() { string source = @" public class C { public event System.Action Event { add { } remove { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var eventSymbol = comp.GlobalNamespace.GetMember<EventSymbol>("C.Event"); Assert.False(eventSymbol.AddMethod.IsInitOnly); Assert.False(eventSymbol.GetPublicSymbol().AddMethod.IsInitOnly); Assert.False(eventSymbol.RemoveMethod.IsInitOnly); Assert.False(eventSymbol.GetPublicSymbol().RemoveMethod.IsInitOnly); } [Fact] public void ConstructorAndDestructorAreNotInitOnly() { string source = @" public class C { public C() { } ~C() { } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var constructor = comp.GlobalNamespace.GetMember<SourceConstructorSymbol>("C..ctor"); Assert.False(constructor.IsInitOnly); Assert.False(constructor.GetPublicSymbol().IsInitOnly); var destructor = comp.GlobalNamespace.GetMember<SourceDestructorSymbol>("C.Finalize"); Assert.False(destructor.IsInitOnly); Assert.False(destructor.GetPublicSymbol().IsInitOnly); } [Fact] public void OperatorsAreNotInitOnly() { string source = @" public class C { public static implicit operator int(C c) => throw null; public static bool operator +(C c1, C c2) => throw null; } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var conversion = comp.GlobalNamespace.GetMember<SourceUserDefinedConversionSymbol>("C.op_Implicit"); Assert.False(conversion.IsInitOnly); Assert.False(conversion.GetPublicSymbol().IsInitOnly); var addition = comp.GlobalNamespace.GetMember<SourceUserDefinedOperatorSymbol>("C.op_Addition"); Assert.False(addition.IsInitOnly); Assert.False(addition.GetPublicSymbol().IsInitOnly); } [Fact] public void ConstructedMethodsAreNotInitOnly() { string source = @" public class C { void M<T>() { M<string>(); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var root = tree.GetCompilationUnitRoot(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: true); var invocation = root.DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var method = (IMethodSymbol)model.GetSymbolInfo(invocation).Symbol; Assert.Equal("void C.M<System.String>()", method.ToTestDisplayString()); Assert.False(method.IsInitOnly); } [Fact] public void InitOnlyOnMembersOfRecords() { string source = @" public record C(int i) { void M() { } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var cMembers = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(); AssertEx.SetEqual(new[] { "C C." + WellKnownMemberNames.CloneMethodName + "()", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "C..ctor(System.Int32 i)", "System.Int32 C.<i>k__BackingField", "System.Int32 C.i.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.i.init", "System.Int32 C.i { get; init; }", "void C.M()", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C..ctor(C original)", "void C.Deconstruct(out System.Int32 i)", }, cMembers.ToTestDisplayStrings()); foreach (var member in cMembers) { if (member is MethodSymbol method) { bool isSetter = method.MethodKind == MethodKind.PropertySet; Assert.Equal(isSetter, method.IsInitOnly); Assert.Equal(isSetter, method.GetPublicSymbol().IsInitOnly); } } } [Fact] public void IndexerWithInitOnly() { string source = @" public class C { public string this[int i] { init { } } public C() { this[42] = null; } public void M1() { this[43] = null; // 1 } } public class Derived : C { public Derived() { this[44] = null; } public void M2() { this[45] = null; // 2 } } public class D { void M3(C c2) { _ = new C() { [46] = null }; c2[47] = null; // 3 } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (14,9): error CS8802: Init-only property or indexer 'C.this[int]' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // this[43] = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "this[43]").WithArguments("C.this[int]").WithLocation(14, 9), // (25,9): error CS8802: Init-only property or indexer 'C.this[int]' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // this[45] = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "this[45]").WithArguments("C.this[int]").WithLocation(25, 9), // (33,9): error CS8802: Init-only property or indexer 'C.this[int]' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c2[47] = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c2[47]").WithArguments("C.this[int]").WithLocation(33, 9) ); } [Fact] public void ReadonlyFields() { string source = @" public class C { public readonly string field; public C() { field = null; } public void M1() { field = null; // 1 _ = new C() { field = null }; // 2 } public int InitOnlyProperty1 { init { field = null; } } public int RegularProperty { get { field = null; // 3 throw null; } set { field = null; // 4 } } } public class Derived : C { public Derived() { field = null; // 5 } public void M2() { field = null; // 6 } public int InitOnlyProperty2 { init { field = null; // 7 } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (11,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the class in which the field is defined or a variable initializer)) // field = null; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(11, 9), // (12,23): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // _ = new C() { field = null }; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(12, 23), // (25,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(25, 13), // (30,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(30, 13), // (38,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 5 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(38, 9), // (42,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 6 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(42, 9), // (48,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 7 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(48, 13) ); } [Fact] public void ReadonlyFields_Evaluation() { string source = @" public class C { public readonly int field; public static void Main() { var c1 = new C(); System.Console.Write($""{c1.field} ""); var c2 = new C() { Property = 43 }; System.Console.Write($""{c2.field}""); } public C() { field = 42; } public int Property { init { field = value; } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); // [ : C::set_Property] Cannot change initonly field outside its .ctor. CompileAndVerify(comp, expectedOutput: "42 43", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails); } [Fact] public void ReadonlyFields_TypesDifferingNullability() { string source = @" public class C { public static void Main() { System.Console.Write(C1<int>.F1.content); System.Console.Write("" ""); System.Console.Write(C2<int>.F1.content); } } public struct Container { public int content; } class C1<T> { public static readonly Container F1; static C1() { C1<T>.F1.content = 2; } } #nullable enable class C2<T> { public static readonly Container F1; static C2() { C2<T>.F1.content = 3; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "2 3", verify: Verification.Skipped); // PEVerify bug // [ : C::Main][mdToken=0x6000004][offset 0x00000001] Cannot change initonly field outside its .ctor. v.VerifyIL("C.Main", @" { // Code size 45 (0x2d) .maxstack 1 IL_0000: nop IL_0001: ldsflda ""Container C1<int>.F1"" IL_0006: ldfld ""int Container.content"" IL_000b: call ""void System.Console.Write(int)"" IL_0010: nop IL_0011: ldstr "" "" IL_0016: call ""void System.Console.Write(string)"" IL_001b: nop IL_001c: ldsflda ""Container C2<int>.F1"" IL_0021: ldfld ""int Container.content"" IL_0026: call ""void System.Console.Write(int)"" IL_002b: nop IL_002c: ret } "); } [Fact] public void StaticReadonlyFieldInitializedByAnother() { string source = @" public class C { public static readonly int field; public static readonly int field2 = (field = 42); } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void ReadonlyFields_DisallowedOnOtherInstances() { string source = @" public class C { public readonly string field; public C c; public C() { c.field = null; // 1 } public string InitOnlyProperty { init { c.field = null; // 2 } } } public class Derived : C { Derived() { c.field = null; // 3 } public string InitOnlyProperty2 { init { c.field = null; // 4 } } } public class Caller { void M(C c) { _ = new C() { field = // 5 (c.field = null) // 6 }; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (9,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the class in which the field is defined or a variable initializer)) // c.field = null; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly, "c.field").WithLocation(9, 9), // (16,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // c.field = null; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly, "c.field").WithLocation(16, 13), // (24,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // c.field = null; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly, "c.field").WithLocation(24, 9), // (31,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // c.field = null; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly, "c.field").WithLocation(31, 13), // (40,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = // 5 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(40, 13), // (41,18): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // (c.field = null) // 6 Diagnostic(ErrorCode.ERR_AssgReadonly, "c.field").WithLocation(41, 18) ); } [Fact, WorkItem(45657, "https://github.com/dotnet/roslyn/issues/45657")] public void ReadonlyFieldsMembers() { string source = @" public struct Container { public string content; } public class C { public readonly Container field; public C() { field.content = null; } public void M1() { field.content = null; // 1 } public int InitOnlyProperty1 { init { field.content = null; } } public int RegularProperty { get { field.content = null; // 2 throw null; } set { field.content = null; // 3 } } } public class Derived : C { public Derived() { field.content = null; // 4 } public void M2() { field.content = null; // 5 } public int InitOnlyProperty2 { init { field.content = null; // 6 } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (15,9): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(15, 9), // (28,13): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(28, 13), // (33,13): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(33, 13), // (41,9): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(41, 9), // (45,9): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 5 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(45, 9), // (51,13): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 6 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(51, 13) ); } [Fact, WorkItem(45657, "https://github.com/dotnet/roslyn/issues/45657")] public void ReadonlyFieldsMembers_Evaluation() { string source = @" public struct Container { public int content; } public class C { public readonly Container field; public int InitOnlyProperty1 { init { field.content = value; System.Console.Write(""RAN ""); } } public static void Main() { var c = new C() { InitOnlyProperty1 = 42 }; System.Console.Write(c.field.content); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN 42", verify: Verification.Skipped /* init-only */); } [Fact, WorkItem(45657, "https://github.com/dotnet/roslyn/issues/45657")] public void ReadonlyFieldsMembers_Static() { string source = @" public struct Container { public int content; } public static class C { public static readonly Container field; public static int InitOnlyProperty1 { init { field.content = value; } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (13,9): error CS8856: The 'init' accessor is not valid on static members // init Diagnostic(ErrorCode.ERR_BadInitAccessor, "init").WithLocation(13, 9), // (15,13): error CS1650: Fields of static readonly field 'C.field' cannot be assigned to (except in a static constructor or a variable initializer) // field.content = value; Diagnostic(ErrorCode.ERR_AssgReadonlyStatic2, "field.content").WithArguments("C.field").WithLocation(15, 13) ); } [Theory] [InlineData(true)] [InlineData(false)] public void ReadonlyFields_Metadata(bool emitAsImage) { string lib_cs = @" public class C { public readonly string field; } "; var libComp = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class Derived : C { public Derived() { field = null; // 1 _ = new C() { field = null }; // 2 } public void M2() { field = null; // 3 _ = new C() { field = null }; // 4 } public int InitOnlyProperty2 { init { field = null; // 5 } } } "; var comp = CreateCompilation(source, references: new[] { emitAsImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the class in which the field is defined or a variable initializer)) // field = null; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(6, 9), // (7,23): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // _ = new C() { field = null }; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(7, 23), // (12,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(12, 9), // (13,23): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // _ = new C() { field = null }; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(13, 23), // (20,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 5 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(20, 13) ); } [Fact] public void TestGetSpeculativeSemanticModelForPropertyAccessorBody() { var compilation = CreateCompilation(@" class R { private int _p; } class C : R { private int M { init { int y = 1000; } } } "); var blockStatement = (BlockSyntax)SyntaxFactory.ParseStatement(@" { int z = 0; _p = 123L; } "); var tree = compilation.SyntaxTrees[0]; var root = tree.GetCompilationUnitRoot(); var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true); AccessorDeclarationSyntax accessorDecl = root.DescendantNodes().OfType<AccessorDeclarationSyntax>().Single(); var speculatedMethod = accessorDecl.ReplaceNode(accessorDecl.Body, blockStatement); SemanticModel speculativeModel; var success = model.TryGetSpeculativeSemanticModelForMethodBody( accessorDecl.Body.Statements[0].SpanStart, speculatedMethod, out speculativeModel); Assert.True(success); Assert.NotNull(speculativeModel); var p = speculativeModel.SyntaxTree.GetRoot() .DescendantNodes() .OfType<IdentifierNameSyntax>() .Single(s => s.Identifier.ValueText == "_p"); var symbolSpeculation = speculativeModel.GetSpeculativeSymbolInfo(p.FullSpan.Start, p, SpeculativeBindingOption.BindAsExpression); Assert.Equal("_p", symbolSpeculation.Symbol.Name); var typeSpeculation = speculativeModel.GetSpeculativeTypeInfo(p.FullSpan.Start, p, SpeculativeBindingOption.BindAsExpression); Assert.Equal("Int32", typeSpeculation.Type.Name); } [Fact] public void BlockBodyAndExpressionBody_14() { var comp = CreateCompilation(new[] { @" public class C { static int P1 { get; set; } int P2 { init { P1 = 1; } => P1 = 1; } } ", IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (7,9): error CS8057: Block bodies and expression bodies cannot both be provided. // init { P1 = 1; } => P1 = 1; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "init { P1 = 1; } => P1 = 1;").WithLocation(7, 9) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>(); Assert.Equal(2, nodes.Count()); foreach (var assign in nodes) { var node = assign.Left; Assert.Equal("P1", node.ToString()); Assert.Equal("System.Int32 C.P1 { get; set; }", model.GetSymbolInfo(node).Symbol.ToTestDisplayString()); } } [Fact] public void ModReqOnSetAccessorParameter() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance void set_Property ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Property() { .set instance void C::set_Property(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override int Property { set { throw null; } } } public class Derived2 : C { public override int Property { init { throw null; } } } public class D { void M(C c) { c.Property = 42; c.set_Property(42); } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,36): error CS0570: 'C.Property.set' is not supported by the language // public override int Property { set { throw null; } } Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("C.Property.set").WithLocation(4, 36), // (8,25): error CS8853: 'Derived2.Property' must match by init-only of overridden member 'C.Property' // public override int Property { init { throw null; } } Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("Derived2.Property", "C.Property").WithLocation(8, 25), // (8,36): error CS0570: 'C.Property.set' is not supported by the language // public override int Property { init { throw null; } } Diagnostic(ErrorCode.ERR_BindToBogus, "init").WithArguments("C.Property.set").WithLocation(8, 36), // (14,11): error CS0570: 'C.Property.set' is not supported by the language // c.Property = 42; Diagnostic(ErrorCode.ERR_BindToBogus, "Property").WithArguments("C.Property.set").WithLocation(14, 11), // (15,11): error CS0571: 'C.Property.set': cannot explicitly call operator or accessor // c.set_Property(42); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_Property").WithArguments("C.Property.set").WithLocation(15, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.Null(property0.GetMethod); Assert.False(property0.MustCallMethodsDirectly); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); var property1 = (PropertySymbol)comp.GlobalNamespace.GetMember("Derived.Property"); Assert.Null(property1.GetMethod); Assert.False(property1.SetMethod.HasUseSiteError); Assert.False(property1.SetMethod.Parameters[0].Type.IsErrorType()); var property2 = (PropertySymbol)comp.GlobalNamespace.GetMember("Derived2.Property"); Assert.Null(property2.GetMethod); Assert.False(property2.SetMethod.HasUseSiteError); Assert.False(property2.SetMethod.Parameters[0].Type.IsErrorType()); } [Fact] public void ModReqOnSetAccessorParameter_AndProperty() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance void set_Property ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) Property() { .set instance void C::set_Property(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override int Property { set { throw null; } } } public class Derived2 : C { public override int Property { init { throw null; } } } public class D { void M(C c) { c.Property = 42; c.set_Property(42); } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,25): error CS0569: 'Derived.Property': cannot override 'C.Property' because it is not supported by the language // public override int Property { set { throw null; } } Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "Property").WithArguments("Derived.Property", "C.Property").WithLocation(4, 25), // (8,25): error CS0569: 'Derived2.Property': cannot override 'C.Property' because it is not supported by the language // public override int Property { init { throw null; } } Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "Property").WithArguments("Derived2.Property", "C.Property").WithLocation(8, 25), // (14,11): error CS1546: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor method 'C.set_Property(int)' // c.Property = 42; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "Property").WithArguments("C.Property", "C.set_Property(int)").WithLocation(14, 11), // (15,11): error CS0570: 'C.set_Property(int)' is not supported by the language // c.set_Property(42); Diagnostic(ErrorCode.ERR_BindToBogus, "set_Property").WithArguments("C.set_Property(int)").WithLocation(15, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.True(property0.HasUseSiteError); Assert.True(property0.HasUnsupportedMetadata); Assert.True(property0.MustCallMethodsDirectly); Assert.Equal("System.Int32", property0.Type.ToTestDisplayString()); Assert.Null(property0.GetMethod); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); var property1 = (PropertySymbol)comp.GlobalNamespace.GetMember("Derived.Property"); Assert.False(property1.HasUseSiteError); Assert.Null(property1.GetMethod); Assert.False(property1.SetMethod.HasUseSiteError); Assert.False(property1.SetMethod.Parameters[0].Type.IsErrorType()); var property2 = (PropertySymbol)comp.GlobalNamespace.GetMember("Derived2.Property"); Assert.False(property2.HasUseSiteError); Assert.Null(property2.GetMethod); Assert.False(property2.SetMethod.HasUseSiteError); Assert.False(property2.SetMethod.Parameters[0].Type.IsErrorType()); } [Fact] public void ModReqOnSetAccessorParameter_IndexerParameter() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .custom instance void System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6d 00 00 ) .method public hidebysig specialname newslot virtual instance void set_Item ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) i, int32 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Item(int32 modreq(System.Runtime.CompilerServices.IsExternalInit) i) { .set instance void C::set_Item(int32 modreq(System.Runtime.CompilerServices.IsExternalInit), int32) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Reflection.DefaultMemberAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor ( string memberName ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override int this[int i] { set { throw null; } } } public class Derived2 : C { public override int this[int i] { init { throw null; } } } public class D { void M(C c) { c[42] = 43; c.set_Item(42, 43); } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,25): error CS0569: 'Derived.this[int]': cannot override 'C.this[int]' because it is not supported by the language // public override int this[int i] { set { throw null; } } Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "this").WithArguments("Derived.this[int]", "C.this[int]").WithLocation(4, 25), // (8,25): error CS0569: 'Derived2.this[int]': cannot override 'C.this[int]' because it is not supported by the language // public override int this[int i] { init { throw null; } } Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "this").WithArguments("Derived2.this[int]", "C.this[int]").WithLocation(8, 25), // (14,9): error CS1546: Property, indexer, or event 'C.this[int]' is not supported by the language; try directly calling accessor method 'C.set_Item(int, int)' // c[42] = 43; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "c[42]").WithArguments("C.this[int]", "C.set_Item(int, int)").WithLocation(14, 9), // (15,11): error CS0570: 'C.set_Item(int, int)' is not supported by the language // c.set_Item(42, 43); Diagnostic(ErrorCode.ERR_BindToBogus, "set_Item").WithArguments("C.set_Item(int, int)").WithLocation(15, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.this[]"); Assert.True(property0.HasUseSiteError); Assert.True(property0.MustCallMethodsDirectly); Assert.Null(property0.GetMethod); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); } [Fact] public void ModReqOnIndexerValue() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .custom instance void System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6d 00 00 ) .method public hidebysig specialname newslot virtual instance void set_Item ( int32 i, int32 modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Item(int32 i) { .set instance void C::set_Item(int32, int32 modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Reflection.DefaultMemberAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor ( string memberName ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override int this[int i] { set { throw null; } } } public class Derived2 : C { public override int this[int i] { init { throw null; } } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,39): error CS0570: 'C.this[int].set' is not supported by the language // public override int this[int i] { set { throw null; } } Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("C.this[int].set").WithLocation(4, 39), // (8,25): error CS8853: 'Derived2.this[int]' must match by init-only of overridden member 'C.this[int]' // public override int this[int i] { init { throw null; } } Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "this").WithArguments("Derived2.this[int]", "C.this[int]").WithLocation(8, 25), // (8,39): error CS0570: 'C.this[int].set' is not supported by the language // public override int this[int i] { init { throw null; } } Diagnostic(ErrorCode.ERR_BindToBogus, "init").WithArguments("C.this[int].set").WithLocation(8, 39) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.this[]"); Assert.False(property0.HasUseSiteError); Assert.False(property0.MustCallMethodsDirectly); Assert.Null(property0.GetMethod); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[1].HasUnsupportedMetadata); } [Fact] public void ModReqOnStaticMethod() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig static void modreq(System.Runtime.CompilerServices.IsExternalInit) M () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void M2() { C.M(); } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,11): error CS0570: 'C.M()' is not supported by the language // C.M(); Diagnostic(ErrorCode.ERR_BindToBogus, "M").WithArguments("C.M()").WithLocation(6, 11) ); var method = (PEMethodSymbol)comp.GlobalNamespace.GetMember("C.M"); Assert.False(method.IsInitOnly); Assert.False(method.GetPublicSymbol().IsInitOnly); Assert.True(method.HasUseSiteError); Assert.True(method.HasUnsupportedMetadata); } [Fact] public void ModReqOnStaticSet() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig newslot specialname static void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 P() { .set void modreq(System.Runtime.CompilerServices.IsExternalInit) C::set_P(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void M2() { C.P = 2; } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,11): error CS0570: 'C.P.set' is not supported by the language // C.P = 2; Diagnostic(ErrorCode.ERR_BindToBogus, "P").WithArguments("C.P.set").WithLocation(6, 11) ); var method = (PEMethodSymbol)comp.GlobalNamespace.GetMember("C.set_P"); Assert.False(method.IsInitOnly); Assert.False(method.GetPublicSymbol().IsInitOnly); Assert.True(method.HasUseSiteError); Assert.True(method.HasUnsupportedMetadata); } [Fact] public void ModReqOnMethodParameter() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig newslot virtual instance void M ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) i ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override void M() { } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,26): error CS0115: 'Derived.M()': no suitable method found to override // public override void M() { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M").WithArguments("Derived.M()").WithLocation(4, 26) ); var method0 = (PEMethodSymbol)comp.GlobalNamespace.GetMember("C.M"); Assert.True(method0.HasUseSiteError); Assert.True(method0.HasUnsupportedMetadata); Assert.True(method0.Parameters[0].HasUnsupportedMetadata); } [Fact] public void ModReqOnInitOnlySetterOfRefProperty() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32& get_Property () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property ( int32& modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32& Property() { .get instance int32& C::get_Property() .set instance void C::set_Property(int32& modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void M(C c, ref int i) { _ = c.get_Property(); c.set_Property(i); // 1 _ = c.Property; // 2 c.Property = i; // 3 } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (7,11): error CS0570: 'C.set_Property(ref int)' is not supported by the language // c.set_Property(i); // 1 Diagnostic(ErrorCode.ERR_BindToBogus, "set_Property").WithArguments("C.set_Property(ref int)").WithLocation(7, 11), // (9,15): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // _ = c.Property; // 2 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(9, 15), // (10,11): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // c.Property = i; // 3 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(10, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property0.HasUseSiteError); Assert.True(property0.MustCallMethodsDirectly); Assert.False(property0.GetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); Assert.False(property0.SetMethod.IsInitOnly); Assert.False(property0.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void ModReqOnRefProperty_OnRefReturn() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) get_Property () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property ( int32& modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) Property() { .get instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) C::get_Property() .set instance void C::set_Property(int32& modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void M(C c, ref int i) { _ = c.get_Property(); // 1 c.set_Property(i); // 2 _ = c.Property; // 3 c.Property = i; // 4 } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,15): error CS0570: 'C.get_Property()' is not supported by the language // _ = c.get_Property(); // 1 Diagnostic(ErrorCode.ERR_BindToBogus, "get_Property").WithArguments("C.get_Property()").WithLocation(6, 15), // (7,11): error CS0570: 'C.set_Property(ref int)' is not supported by the language // c.set_Property(i); // 2 Diagnostic(ErrorCode.ERR_BindToBogus, "set_Property").WithArguments("C.set_Property(ref int)").WithLocation(7, 11), // (9,15): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // _ = c.Property; // 3 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(9, 15), // (10,11): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // c.Property = i; // 4 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(10, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.True(property0.HasUseSiteError); Assert.True(property0.MustCallMethodsDirectly); Assert.Equal("System.Runtime.CompilerServices.IsExternalInit", property0.RefCustomModifiers.Single().Modifier.ToTestDisplayString()); Assert.Empty(property0.TypeWithAnnotations.CustomModifiers); Assert.True(property0.GetMethod.HasUseSiteError); Assert.True(property0.GetMethod.HasUnsupportedMetadata); Assert.True(property0.GetMethod.ReturnsByRef); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); Assert.False(property0.SetMethod.IsInitOnly); Assert.False(property0.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void ModReqOnRefProperty_OnReturn() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& get_Property () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& Property() { .get instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& C::get_Property() .set instance void C::set_Property(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)&) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void M(C c, ref int i) { _ = c.get_Property(); // 1 c.set_Property(i); // 2 _ = c.Property; // 3 c.Property = i; // 4 } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,15): error CS0570: 'C.get_Property()' is not supported by the language // _ = c.get_Property(); // 1 Diagnostic(ErrorCode.ERR_BindToBogus, "get_Property").WithArguments("C.get_Property()").WithLocation(6, 15), // (7,11): error CS0570: 'C.set_Property(ref int)' is not supported by the language // c.set_Property(i); // 2 Diagnostic(ErrorCode.ERR_BindToBogus, "set_Property").WithArguments("C.set_Property(ref int)").WithLocation(7, 11), // (9,15): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // _ = c.Property; // 3 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(9, 15), // (10,11): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // c.Property = i; // 4 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(10, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.True(property0.HasUseSiteError); Assert.True(property0.MustCallMethodsDirectly); Assert.Empty(property0.RefCustomModifiers); Assert.Equal("System.Runtime.CompilerServices.IsExternalInit", property0.TypeWithAnnotations.CustomModifiers.Single().Modifier.ToTestDisplayString()); Assert.Equal("System.Int32", property0.TypeWithAnnotations.Type.ToTestDisplayString()); Assert.True(property0.GetMethod.HasUseSiteError); Assert.True(property0.GetMethod.HasUnsupportedMetadata); Assert.True(property0.GetMethod.ReturnsByRef); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); Assert.False(property0.SetMethod.IsInitOnly); Assert.False(property0.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void ModReqOnGetAccessorReturnValue() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) get_Property () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property ( int32 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Property() { .get instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) C::get_Property() .set instance void C::set_Property(int32) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override int Property { get { throw null; } } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,36): error CS0570: 'C.Property.get' is not supported by the language // public override int Property { get { throw null; } } Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("C.Property.get").WithLocation(4, 36) ); var property = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().GetMethod.IsInitOnly); Assert.True(property.GetMethod.HasUseSiteError); Assert.True(property.GetMethod.HasUnsupportedMetadata); Assert.False(property.SetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().SetMethod.IsInitOnly); Assert.False(property.SetMethod.HasUseSiteError); } [Fact] public void TestSyntaxFacts() { Assert.True(SyntaxFacts.IsAccessorDeclaration(SyntaxKind.InitAccessorDeclaration)); Assert.True(SyntaxFacts.IsAccessorDeclarationKeyword(SyntaxKind.InitKeyword)); } [Fact] public void NoCascadingErrorsInStaticConstructor() { string source = @" public class C { public string Property { get { throw null; } init { throw null; } } static C() { Property = null; // 1 this.Property = null; // 2 } } public class D : C { static D() { Property = null; // 3 this.Property = null; // 4 base.Property = null; // 5 } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (7,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // Property = null; // 1 Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(7, 9), // (8,9): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // this.Property = null; // 2 Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this").WithLocation(8, 9), // (15,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // Property = null; // 3 Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(15, 9), // (16,9): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // this.Property = null; // 4 Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this").WithLocation(16, 9), // (17,9): error CS1511: Keyword 'base' is not available in a static method // base.Property = null; // 5 Diagnostic(ErrorCode.ERR_BaseInStaticMeth, "base").WithLocation(17, 9) ); } [Fact] public void LocalFunctionsAreNotInitOnly() { var comp = CreateCompilation(new[] { @" public class C { delegate void Delegate(); void M() { local(); void local() { } } } ", IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var localFunctionSyntax = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var localFunctionSymbol = model.GetDeclaredSymbol(localFunctionSyntax).GetSymbol<LocalFunctionSymbol>(); Assert.False(localFunctionSymbol.IsInitOnly); Assert.False(localFunctionSymbol.GetPublicSymbol().IsInitOnly); var delegateSyntax = tree.GetRoot().DescendantNodes().OfType<DelegateDeclarationSyntax>().Single(); var delegateMemberSymbols = model.GetDeclaredSymbol(delegateSyntax).GetSymbol<SourceNamedTypeSymbol>().GetMembers(); Assert.True(delegateMemberSymbols.All(m => m is SourceDelegateMethodSymbol)); foreach (var member in delegateMemberSymbols) { if (member is MethodSymbol method) { Assert.False(method.IsInitOnly); Assert.False(method.GetPublicSymbol().IsInitOnly); } } } [Fact] public void RetargetProperties_WithInitOnlySetter() { var source0 = @" public struct S { public int Property { get; init; } } "; var source1 = @" class Program { public static void Main() { var s = new S() { Property = 42 }; System.Console.WriteLine(s.Property); } } "; var source2 = @" class Program { public static void Main() { var s = new S() { Property = 43 }; System.Console.WriteLine(s.Property); } } "; var comp1 = CreateCompilation(new[] { source0, source1, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); // PEVerify: [ : S::set_Property] Cannot change initonly field outside its .ctor. CompileAndVerify(comp1, expectedOutput: "42", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails); var comp1Ref = new[] { comp1.ToMetadataReference() }; var comp7 = CreateCompilation(source2, references: comp1Ref, targetFramework: TargetFramework.Mscorlib46, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); CompileAndVerify(comp7, expectedOutput: "43"); var property = comp7.GetMember<PropertySymbol>("S.Property"); var setter = (RetargetingMethodSymbol)property.SetMethod; Assert.True(setter.IsInitOnly); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyStruct_AutoProp() { var verifier = CompileAndVerify(new[] { IsExternalInitTypeDefinition, @" var s = new S { I = 1 }; System.Console.Write(s.I); public readonly struct S { public int I { get; init; } } " }, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails, expectedOutput: "1"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (S V_0, //s S V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: call ""void S.I.init"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: call ""int S.I.get"" IL_0019: call ""void System.Console.Write(int)"" IL_001e: ret } "); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyStruct_ManualProp() { var verifier = CompileAndVerify(new[] { IsExternalInitTypeDefinition, @" var s = new S { I = 1 }; System.Console.Write(s.I); public readonly struct S { private readonly int i; public int I { get => i; init => i = value; } } " }, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails, expectedOutput: "1"); var s = verifier.Compilation.GetTypeByMetadataName("S"); var i = s.GetMember<IPropertySymbol>("I"); Assert.False(i.SetMethod.IsReadOnly); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (S V_0, //s S V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: call ""void S.I.init"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: call ""int S.I.get"" IL_0019: call ""void System.Console.Write(int)"" IL_001e: ret } "); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyProperty_AutoProp() { var verifier = CompileAndVerify(new[] { IsExternalInitTypeDefinition, @" var s = new S { I = 1 }; System.Console.Write(s.I); public struct S { public readonly int I { get; init; } } " }, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails, expectedOutput: "1"); var s = verifier.Compilation.GetTypeByMetadataName("S"); var i = s.GetMember<IPropertySymbol>("I"); Assert.False(i.SetMethod.IsReadOnly); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (S V_0, //s S V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: call ""void S.I.init"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: call ""readonly int S.I.get"" IL_0019: call ""void System.Console.Write(int)"" IL_001e: ret } "); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyProperty_ManualProp() { var verifier = CompileAndVerify(new[] { IsExternalInitTypeDefinition, @" var s = new S { I = 1 }; System.Console.Write(s.I); public struct S { private readonly int i; public readonly int I { get => i; init => i = value; } } " }, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails, expectedOutput: "1"); var s = verifier.Compilation.GetTypeByMetadataName("S"); var i = s.GetMember<IPropertySymbol>("I"); Assert.False(i.SetMethod.IsReadOnly); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (S V_0, //s S V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: call ""void S.I.init"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: call ""readonly int S.I.get"" IL_0019: call ""void System.Console.Write(int)"" IL_001e: ret } "); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyInit_AutoProp() { var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, @" public struct S { public int I { get; readonly init; } } " }); comp.VerifyDiagnostics( // (4,34): error CS8903: 'init' accessors cannot be marked 'readonly'. Mark 'S.I' readonly instead. // public int I { get; readonly init; } Diagnostic(ErrorCode.ERR_InitCannotBeReadonly, "init", isSuppressed: false).WithArguments("S.I").WithLocation(4, 34) ); var s = ((Compilation)comp).GetTypeByMetadataName("S"); var i = s.GetMember<IPropertySymbol>("I"); Assert.False(i.SetMethod.IsReadOnly); Assert.True(((Symbols.PublicModel.PropertySymbol)i).GetSymbol<PropertySymbol>().SetMethod.IsDeclaredReadOnly); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyInit_ManualProp() { var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, @" public struct S { public int I { get => 1; readonly init { } } } " }); comp.VerifyDiagnostics( // (4,39): error CS8903: 'init' accessors cannot be marked 'readonly'. Mark 'S.I' readonly instead. // public int I { get => 1; readonly init { } } Diagnostic(ErrorCode.ERR_InitCannotBeReadonly, "init", isSuppressed: false).WithArguments("S.I").WithLocation(4, 39) ); var s = ((Compilation)comp).GetTypeByMetadataName("S"); var i = s.GetMember<IPropertySymbol>("I"); Assert.False(i.SetMethod.IsReadOnly); Assert.True(((Symbols.PublicModel.PropertySymbol)i).GetSymbol<PropertySymbol>().SetMethod.IsDeclaredReadOnly); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyInit_ReassignsSelf() { var verifier = CompileAndVerify(new[] { IsExternalInitTypeDefinition, @" var s = new S { I1 = 1, I2 = 2 }; System.Console.WriteLine($""I1 is {s.I1}""); public readonly struct S { private readonly int i; public readonly int I1 { get => i; init => i = value; } public int I2 { get => throw null; init { System.Console.WriteLine($""I1 was {I1}""); this = default; } } } " }, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails, expectedOutput: @"I1 was 1 I1 is 0"); var s = verifier.Compilation.GetTypeByMetadataName("S"); var i1 = s.GetMember<IPropertySymbol>("I1"); Assert.False(i1.SetMethod.IsReadOnly); var i2 = s.GetMember<IPropertySymbol>("I2"); Assert.False(i2.SetMethod.IsReadOnly); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 54 (0x36) .maxstack 2 .locals init (S V_0, //s S V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: call ""void S.I1.init"" IL_0010: ldloca.s V_1 IL_0012: ldc.i4.2 IL_0013: call ""void S.I2.init"" IL_0018: ldloc.1 IL_0019: stloc.0 IL_001a: ldstr ""I1 is {0}"" IL_001f: ldloca.s V_0 IL_0021: call ""int S.I1.get"" IL_0026: box ""int"" IL_002b: call ""string string.Format(string, object)"" IL_0030: call ""void System.Console.WriteLine(string)"" IL_0035: ret } "); } [Fact] [WorkItem(50126, "https://github.com/dotnet/roslyn/issues/50126")] public void NestedInitializer() { var source = @" using System; Person person = new Person(""j"", ""p""); Container c = new Container(person) { Person = { FirstName = ""c"" } }; public record Person(String FirstName, String LastName); public record Container(Person Person); "; var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, source }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (7,16): error CS8852: Init-only property or indexer 'Person.FirstName' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Person = { FirstName = "c" } Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "FirstName").WithArguments("Person.FirstName").WithLocation(7, 16) ); } [Fact] [WorkItem(50126, "https://github.com/dotnet/roslyn/issues/50126")] public void NestedInitializer_NewT() { var source = @" using System; class C { void M<T>(Person person) where T : Container, new() { Container c = new T() { Person = { FirstName = ""c"" } }; } } public record Person(String FirstName, String LastName); public record Container(Person Person); "; var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, source }); comp.VerifyEmitDiagnostics( // (10,24): error CS8852: Init-only property or indexer 'Person.FirstName' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Person = { FirstName = "c" } Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "FirstName").WithArguments("Person.FirstName").WithLocation(10, 24) ); } [Fact] [WorkItem(50126, "https://github.com/dotnet/roslyn/issues/50126")] public void NestedInitializer_UsingGenericType() { var source = @" using System; Person person = new Person(""j"", ""p""); var c = new Container<Person>(person) { PropertyT = { FirstName = ""c"" } }; public record Person(String FirstName, String LastName); public record Container<T>(T PropertyT) where T : Person; "; var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, source }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (7,19): error CS8852: Init-only property or indexer 'Person.FirstName' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // PropertyT = { FirstName = "c" } Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "FirstName").WithArguments("Person.FirstName").WithLocation(7, 19) ); } [Fact] [WorkItem(50126, "https://github.com/dotnet/roslyn/issues/50126")] public void NestedInitializer_UsingNew() { var source = @" using System; Person person = new Person(""j"", ""p""); Container c = new Container(person) { Person = new Person(""j"", ""p"") { FirstName = ""c"" } }; Console.Write(c.Person.FirstName); public record Person(String FirstName, String LastName); public record Container(Person Person); "; var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, source }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); // PEVerify: Cannot change initonly field outside its .ctor. CompileAndVerify(comp, expectedOutput: "c", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails); } [Fact] [WorkItem(50126, "https://github.com/dotnet/roslyn/issues/50126")] public void NestedInitializer_UsingNewNoPia() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58277"")] [CoClass(typeof(ClassITest28))] public interface ITest28 { int Property { get; init; } } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest28 //: ITest28 { public ClassITest28(int x) { } } "; var piaCompilation = CreateCompilationWithMscorlib45(new[] { IsExternalInitTypeDefinition, pia }, options: TestOptions.DebugDll); CompileAndVerify(piaCompilation); string source = @" class UsePia { public ITest28 Property2 { get; init; } public static void Main() { var x1 = new ITest28() { Property = 42 }; var x2 = new UsePia() { Property2 = { Property = 43 } }; } }"; var compilation = CreateCompilationWithMscorlib45(new[] { source }, new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) }, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (9,47): error CS8852: Init-only property or indexer 'ITest28.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // var x2 = new UsePia() { Property2 = { Property = 43 } }; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("ITest28.Property").WithLocation(9, 47) ); } [Fact, WorkItem(50696, "https://github.com/dotnet/roslyn/issues/50696")] public void PickAmbiguousTypeFromCorlib() { var corlib_cs = @" namespace System { public class Object { } public struct Int32 { } public struct Boolean { } public class String { } public class ValueType { } public struct Void { } public class Attribute { } } "; string source = @" public class C { public int Property { get; init; } } "; var corlibWithoutIsExternalInitRef = CreateEmptyCompilation(corlib_cs, assemblyName: "corlibWithoutIsExternalInit") .EmitToImageReference(); var corlibWithIsExternalInitRef = CreateEmptyCompilation(corlib_cs + IsExternalInitTypeDefinition, assemblyName: "corlibWithIsExternalInit") .EmitToImageReference(); var libWithIsExternalInitRef = CreateEmptyCompilation(IsExternalInitTypeDefinition, references: new[] { corlibWithoutIsExternalInitRef }, assemblyName: "libWithIsExternalInit") .EmitToImageReference(); var libWithIsExternalInitRef2 = CreateEmptyCompilation(IsExternalInitTypeDefinition, references: new[] { corlibWithoutIsExternalInitRef }, assemblyName: "libWithIsExternalInit2") .EmitToImageReference(); { // type in source var comp = CreateEmptyCompilation(new[] { source, IsExternalInitTypeDefinition }, references: new[] { corlibWithoutIsExternalInitRef }, assemblyName: "source"); comp.VerifyEmitDiagnostics(); verify(comp, "source"); } { // type in library var comp = CreateEmptyCompilation(new[] { source }, references: new[] { corlibWithoutIsExternalInitRef, libWithIsExternalInitRef }, assemblyName: "source"); comp.VerifyEmitDiagnostics(); verify(comp, "libWithIsExternalInit"); } { // type in corlib and in source var comp = CreateEmptyCompilation(new[] { source, IsExternalInitTypeDefinition }, references: new[] { corlibWithIsExternalInitRef }, assemblyName: "source"); comp.VerifyEmitDiagnostics(); verify(comp, "source"); } { // type in corlib, in library and in source var comp = CreateEmptyCompilation(new[] { source, IsExternalInitTypeDefinition }, references: new[] { corlibWithIsExternalInitRef, libWithIsExternalInitRef }, assemblyName: "source"); comp.VerifyEmitDiagnostics(); verify(comp, "source"); } { // type in corlib and in two libraries var comp = CreateEmptyCompilation(source, references: new[] { corlibWithIsExternalInitRef, libWithIsExternalInitRef, libWithIsExternalInitRef2 }); comp.VerifyEmitDiagnostics(); verify(comp, "corlibWithIsExternalInit"); } { // type in corlib and in two libraries (corlib in middle) var comp = CreateEmptyCompilation(source, references: new[] { libWithIsExternalInitRef, corlibWithIsExternalInitRef, libWithIsExternalInitRef2 }); comp.VerifyEmitDiagnostics(); verify(comp, "corlibWithIsExternalInit"); } { // type in corlib and in two libraries (corlib last) var comp = CreateEmptyCompilation(source, references: new[] { libWithIsExternalInitRef, libWithIsExternalInitRef2, corlibWithIsExternalInitRef }); comp.VerifyEmitDiagnostics(); verify(comp, "corlibWithIsExternalInit"); } { // type in corlib and in two libraries, but flag is set var comp = CreateEmptyCompilation(source, references: new[] { corlibWithIsExternalInitRef, libWithIsExternalInitRef, libWithIsExternalInitRef2 }, options: TestOptions.DebugDll.WithTopLevelBinderFlags(BinderFlags.IgnoreCorLibraryDuplicatedTypes)); comp.VerifyEmitDiagnostics( // (4,32): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported // public int Property { get; init; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit").WithLocation(4, 32) ); } { // type in two libraries var comp = CreateEmptyCompilation(source, references: new[] { corlibWithoutIsExternalInitRef, libWithIsExternalInitRef, libWithIsExternalInitRef2 }); comp.VerifyEmitDiagnostics( // (4,32): error CS018: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported // public int Property { get; init; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit").WithLocation(4, 32) ); } { // type in two libraries, but flag is set var comp = CreateEmptyCompilation(source, references: new[] { corlibWithoutIsExternalInitRef, libWithIsExternalInitRef, libWithIsExternalInitRef2 }, options: TestOptions.DebugDll.WithTopLevelBinderFlags(BinderFlags.IgnoreCorLibraryDuplicatedTypes)); comp.VerifyEmitDiagnostics( // (4,32): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported // public int Property { get; init; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit").WithLocation(4, 32) ); } { // type in corlib and in a library var comp = CreateEmptyCompilation(source, references: new[] { corlibWithIsExternalInitRef, libWithIsExternalInitRef }); comp.VerifyEmitDiagnostics(); verify(comp, "corlibWithIsExternalInit"); } { // type in corlib and in a library (reverse order) var comp = CreateEmptyCompilation(source, references: new[] { libWithIsExternalInitRef, corlibWithIsExternalInitRef }); comp.VerifyEmitDiagnostics(); verify(comp, "corlibWithIsExternalInit"); } { // type in corlib and in a library, but flag is set var comp = CreateEmptyCompilation(source, references: new[] { corlibWithIsExternalInitRef, libWithIsExternalInitRef }, options: TestOptions.DebugDll.WithTopLevelBinderFlags(BinderFlags.IgnoreCorLibraryDuplicatedTypes)); comp.VerifyEmitDiagnostics(); Assert.Equal("libWithIsExternalInit", comp.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IsExternalInit).ContainingAssembly.Name); Assert.Equal("corlibWithIsExternalInit", comp.GetTypeByMetadataName("System.Runtime.CompilerServices.IsExternalInit").ContainingAssembly.Name); } static void verify(CSharpCompilation comp, string expectedAssemblyName) { var modifier = ((SourcePropertySymbol)comp.GlobalNamespace.GetMember("C.Property")).SetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single(); Assert.Equal(expectedAssemblyName, modifier.Modifier.ContainingAssembly.Name); Assert.Equal(expectedAssemblyName, comp.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IsExternalInit).ContainingAssembly.Name); Assert.Equal(expectedAssemblyName, comp.GetTypeByMetadataName("System.Runtime.CompilerServices.IsExternalInit").ContainingAssembly.Name); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { [CompilerTrait(CompilerFeature.InitOnlySetters)] public class InitOnlyMemberTests : CompilingTestBase { // Spec: https://github.com/dotnet/csharplang/blob/main/proposals/init.md // https://github.com/dotnet/roslyn/issues/44685 // test dynamic scenario // test whether reflection use property despite modreq? // test behavior of old compiler with modreq. For example VB [Fact] public void TestCSharp8() { string source = @" public class C { public string Property { get; init; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyEmitDiagnostics( // (4,35): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // public string Property { get; init; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "init").WithArguments("init-only setters", "9.0").WithLocation(4, 35) ); var property = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.True(property.SetMethod.IsInitOnly); IPropertySymbol publicProperty = property.GetPublicSymbol(); Assert.False(publicProperty.GetMethod.IsInitOnly); Assert.True(publicProperty.SetMethod.IsInitOnly); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionInObjectInitializer(bool useMetadataImage) { string lib_cs = @" public class C { public string Property { get; init; } public string Property2 { get; } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class D { void M() { _ = new C() { Property = string.Empty, Property2 = string.Empty }; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (6,23): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = new C() { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Property").WithArguments("init-only setters", "9.0").WithLocation(6, 23), // (6,48): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = new C() { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(6, 48) ); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionInNestedObjectInitializer(bool useMetadataImage) { string lib_cs = @" public class C { public string Property { get; init; } public string Property2 { get; } } public class Container { public C contained; } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class D { void M(C c) { _ = new Container() { contained = { Property = string.Empty, Property2 = string.Empty } }; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (6,45): error CS8852: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // _ = new Container() { contained = { Property = string.Empty, Property2 = string.Empty } }; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(6, 45), // (6,70): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = new Container() { contained = { Property = string.Empty, Property2 = string.Empty } }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(6, 70) ); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionInWithExpression(bool useMetadataImage) { string lib_cs = @" public record C { public string Property { get; init; } public string Property2 { get; } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class D { void M(C c) { _ = c with { Property = string.Empty, Property2 = string.Empty }; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (6,15): error CS8400: Feature 'records' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = c with { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "with").WithArguments("records", "9.0").WithLocation(6, 15), // (6,22): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = c with { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Property").WithArguments("init-only setters", "9.0").WithLocation(6, 22), // (6,47): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = c with { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(6, 47) ); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionInAssignment(bool useMetadataImage) { string lib_cs = @" public record C { public string Property { get; init; } public string Property2 { get; } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class D { void M(C c) { c.Property = string.Empty; c.Property2 = string.Empty; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (6,9): error CS8852: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = string.Empty; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(6, 9), // (7,9): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // c.Property2 = string.Empty; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "c.Property2").WithArguments("C.Property2").WithLocation(7, 9) ); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionInAttribute(bool useMetadataImage) { string lib_cs = @" public class TestAttribute : System.Attribute { public int Property { get; init; } public int Property2 { get; } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" [Test(Property = 42, Property2 = 43)] class C { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (2,7): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // [Test(Property = 42, Property2 = 43)] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Property = 42").WithArguments("init-only setters", "9.0").WithLocation(2, 7), // (2,22): error CS0617: 'Property2' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [Test(Property = 42, Property2 = 43)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "Property2").WithArguments("Property2").WithLocation(2, 22) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (2,22): error CS0617: 'Property2' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [Test(Property = 42, Property2 = 43)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "Property2").WithArguments("Property2").WithLocation(2, 22) ); } [Fact, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionWithinSameCompilation() { string source = @" class C { string Property { get; init; } string Property2 { get; } void M(C c) { _ = new C() { Property = string.Empty, Property2 = string.Empty }; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyEmitDiagnostics( // (4,28): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // string Property { get; init; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "init").WithArguments("init-only setters", "9.0").WithLocation(4, 28), // (9,48): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = new C() { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(9, 48) ); } [Fact, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionWithinSameCompilation_InAttribute() { string source = @" public class TestAttribute : System.Attribute { public int Property { get; init; } public int Property2 { get; } } [Test(Property = 42, Property2 = 43)] class C { } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyEmitDiagnostics( // (4,32): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // public int Property { get; init; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "init").WithArguments("init-only setters", "9.0").WithLocation(4, 32), // (8,22): error CS0617: 'Property2' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [Test(Property = 42, Property2 = 43)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "Property2").WithArguments("Property2").WithLocation(8, 22) ); } [Fact, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionFromCompilationReference() { string lib_cs = @" public class C { public string Property { get; init; } public string Property2 { get; } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular8, assemblyName: "lib"); string source = @" public class D { void M() { _ = new C() { Property = string.Empty, Property2 = string.Empty }; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { lib.ToMetadataReference() }, assemblyName: "comp"); comp.VerifyEmitDiagnostics( // (6,23): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = new C() { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Property").WithArguments("init-only setters", "9.0").WithLocation(6, 23), // (6,48): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = new C() { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(6, 48) ); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionWithDynamicArgument(bool useMetadataImage) { string lib_cs = @" public class C { public string Property { get; init; } public string Property2 { get; } public C(int i) { } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class D { void M(dynamic d) { _ = new C(d) { Property = string.Empty, Property2 = string.Empty }; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (6,24): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = new C(d) { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Property").WithArguments("init-only setters", "9.0").WithLocation(6, 24), // (6,49): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = new C(d) { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(6, 49) ); } [Fact] public void TestInitNotModifier() { string source = @" public class C { public string Property { get; init set; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,40): error CS8180: { or ; or => expected // public string Property { get; init set; } Diagnostic(ErrorCode.ERR_SemiOrLBraceOrArrowExpected, "set").WithLocation(4, 40), // (4,40): error CS1007: Property accessor already defined // public string Property { get; init set; } Diagnostic(ErrorCode.ERR_DuplicateAccessor, "set").WithLocation(4, 40) ); } [Fact] public void TestWithDuplicateAccessor() { string source = @" public class C { public string Property { set => throw null; init => throw null; } public string Property2 { init => throw null; set => throw null; } public string Property3 { init => throw null; init => throw null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,49): error CS1007: Property accessor already defined // public string Property { set => throw null; init => throw null; } Diagnostic(ErrorCode.ERR_DuplicateAccessor, "init").WithLocation(4, 49), // (5,51): error CS1007: Property accessor already defined // public string Property2 { init => throw null; set => throw null; } Diagnostic(ErrorCode.ERR_DuplicateAccessor, "set").WithLocation(5, 51), // (6,51): error CS1007: Property accessor already defined // public string Property3 { init => throw null; init => throw null; } Diagnostic(ErrorCode.ERR_DuplicateAccessor, "init").WithLocation(6, 51) ); var members = ((NamedTypeSymbol)comp.GlobalNamespace.GetMember("C")).GetMembers(); AssertEx.SetEqual(members.ToTestDisplayStrings(), new[] { "System.String C.Property { set; }", "void C.Property.set", "System.String C.Property2 { init; }", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.Property2.init", "System.String C.Property3 { init; }", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.Property3.init", "C..ctor()" }); var property = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property.SetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().SetMethod.IsInitOnly); var property2 = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property2"); Assert.True(property2.SetMethod.IsInitOnly); Assert.True(property2.GetPublicSymbol().SetMethod.IsInitOnly); var property3 = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property3"); Assert.True(property3.SetMethod.IsInitOnly); Assert.True(property3.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void InThisOrBaseConstructorInitializer() { string source = @" public class C { public string Property { init { throw null; } } public C() : this(Property = null) // 1 { } public C(string s) { } } public class Derived : C { public Derived() : base(Property = null) // 2 { } public Derived(int i) : base(base.Property = null) // 3 { } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (5,23): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // public C() : this(Property = null) // 1 Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(5, 23), // (15,29): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // public Derived() : base(Property = null) // 2 Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(15, 29), // (19,34): error CS1512: Keyword 'base' is not available in the current context // public Derived(int i) : base(base.Property = null) // 3 Diagnostic(ErrorCode.ERR_BaseInBadContext, "base").WithLocation(19, 34) ); } [Fact] public void TestWithAccessModifiers_Private() { string source = @" public class C { public string Property { get { throw null; } private init { throw null; } } void M() { _ = new C() { Property = null }; Property = null; // 1 } C() { Property = null; } } public class Other { void M(C c) { _ = new C() { Property = null }; // 2, 3 c.Property = null; // 4 } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9), // (20,17): error CS0122: 'C.C()' is inaccessible due to its protection level // _ = new C() { Property = null }; // 2, 3 Diagnostic(ErrorCode.ERR_BadAccess, "C").WithArguments("C.C()").WithLocation(20, 17), // (20,23): error CS0272: The property or indexer 'C.Property' cannot be used in this context because the set accessor is inaccessible // _ = new C() { Property = null }; // 2, 3 Diagnostic(ErrorCode.ERR_InaccessibleSetter, "Property").WithArguments("C.Property").WithLocation(20, 23), // (21,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(21, 9) ); } [Fact] public void TestWithAccessModifiers_Protected() { string source = @" public class C { public string Property { get { throw null; } protected init { throw null; } } void M() { _ = new C() { Property = null }; Property = null; // 1 } public C() { Property = null; } } public class Derived : C { void M(C c) { _ = new C() { Property = null }; // 2 c.Property = null; // 3, 4 Property = null; // 5 } Derived() { _ = new C() { Property = null }; // 6 _ = new Derived() { Property = null }; Property = null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9), // (20,23): error CS1540: Cannot access protected member 'C.Property' via a qualifier of type 'C'; the qualifier must be of type 'Derived' (or derived from it) // _ = new C() { Property = null }; // 2 Diagnostic(ErrorCode.ERR_BadProtectedAccess, "Property").WithArguments("C.Property", "C", "Derived").WithLocation(20, 23), // (21,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 3, 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(21, 9), // (22,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 5 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(22, 9), // (27,23): error CS1540: Cannot access protected member 'C.Property' via a qualifier of type 'C'; the qualifier must be of type 'Derived' (or derived from it) // _ = new C() { Property = null }; // 6 Diagnostic(ErrorCode.ERR_BadProtectedAccess, "Property").WithArguments("C.Property", "C", "Derived").WithLocation(27, 23) ); } [Fact] public void TestWithAccessModifiers_Protected_WithoutGetter() { string source = @" public class C { public string Property { protected init { throw null; } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,19): error CS0276: 'C.Property': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // public string Property { protected init { throw null; } } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "Property").WithArguments("C.Property").WithLocation(4, 19) ); } [Fact] public void OverrideScenarioWithSubstitutions() { string source = @" public class C<T> { public string Property { get; init; } } public class Derived : C<string> { void M() { Property = null; // 1 } Derived() { Property = null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (10,9): error CS8802: Init-only property or indexer 'C<string>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<string>.Property").WithLocation(10, 9) ); var property = (PropertySymbol)comp.GlobalNamespace.GetTypeMember("Derived").BaseTypeNoUseSiteDiagnostics.GetMember("Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().GetMethod.IsInitOnly); Assert.True(property.SetMethod.IsInitOnly); Assert.True(property.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void ImplementationScenarioWithSubstitutions() { string source = @" public interface I<T> { public string Property { get; init; } } public class CWithInit : I<string> { public string Property { get; init; } } public class CWithoutInit : I<string> // 1 { public string Property { get; set; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (10,29): error CS8804: 'CWithoutInit' does not implement interface member 'I<string>.Property.init'. 'CWithoutInit.Property.set' cannot implement 'I<string>.Property.init'. // public class CWithoutInit : I<string> // 1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I<string>").WithArguments("CWithoutInit", "I<string>.Property.init", "CWithoutInit.Property.set").WithLocation(10, 29) ); var property = (PropertySymbol)comp.GlobalNamespace.GetMember("I.Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().GetMethod.IsInitOnly); Assert.True(property.SetMethod.IsInitOnly); Assert.True(property.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void InLambdaOrLocalFunction_InMethodOrDerivedConstructor() { string source = @" public class C<T> { public string Property { get; init; } } public class Derived : C<string> { void M() { System.Action a = () => { Property = null; // 1 }; local(); void local() { Property = null; // 2 } } Derived() { System.Action a = () => { Property = null; // 3 }; local(); void local() { Property = null; // 4 } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (12,13): error CS8802: Init-only property or indexer 'C<string>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<string>.Property").WithLocation(12, 13), // (18,13): error CS8802: Init-only property or indexer 'C<string>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<string>.Property").WithLocation(18, 13), // (26,13): error CS8802: Init-only property or indexer 'C<string>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<string>.Property").WithLocation(26, 13), // (32,13): error CS8802: Init-only property or indexer 'C<string>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<string>.Property").WithLocation(32, 13) ); } [Fact] public void InLambdaOrLocalFunction_InConstructorOrInit() { string source = @" public class C<T> { public string Property { get; init; } C() { System.Action a = () => { Property = null; // 1 }; local(); void local() { Property = null; // 2 } } public string Other { init { System.Action a = () => { Property = null; // 3 }; local(); void local() { Property = null; // 4 } } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (10,13): error CS8802: Init-only property or indexer 'C<T>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<T>.Property").WithLocation(10, 13), // (16,13): error CS8802: Init-only property or indexer 'C<T>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<T>.Property").WithLocation(16, 13), // (26,17): error CS8802: Init-only property or indexer 'C<T>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<T>.Property").WithLocation(26, 17), // (32,17): error CS8802: Init-only property or indexer 'C<T>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<T>.Property").WithLocation(32, 17) ); } [Fact] public void MissingIsInitOnlyType_Property() { string source = @" public class C { public string Property { get => throw null; init { } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,49): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported // public string Property { get => throw null; init { } } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit").WithLocation(4, 49) ); } [Fact] public void InitOnlyPropertyAssignmentDisallowed() { string source = @" public class C { public string Property { get; init; } void M() { Property = null; // 1 _ = new C() { Property = null }; } public C() { Property = null; } public string InitOnlyProperty { get { Property = null; // 2 return null; } init { Property = null; } } public string RegularProperty { get { Property = null; // 3 return null; } set { Property = null; // 4 } } public string otherField = (Property = null); // 5 } class Derived : C { } class Derived2 : Derived { void M() { Property = null; // 6 } Derived2() { Property = null; } public string InitOnlyProperty2 { get { Property = null; // 7 return null; } init { Property = null; } } public string RegularProperty2 { get { Property = null; // 8 return null; } set { Property = null; // 9 } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9), // (21,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(21, 13), // (34,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(34, 13), // (39,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(39, 13), // (43,33): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.Property' // public string otherField = (Property = null); // 5 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "Property").WithArguments("C.Property").WithLocation(43, 33), // (54,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 6 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(54, 9), // (66,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 7 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(66, 13), // (79,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 8 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(79, 13), // (84,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 9 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(84, 13) ); var property = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().GetMethod.IsInitOnly); Assert.True(property.SetMethod.IsInitOnly); Assert.True(property.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void InitOnlyPropertyAssignmentAllowedInWithInitializer() { string source = @" record C { public int Property { get; init; } void M(C c) { _ = c with { Property = 1 }; } } record Derived : C { } record Derived2 : Derived { void M(C c) { _ = c with { Property = 1 }; _ = this with { Property = 1 }; } } class Other { void M() { var c = new C() with { Property = 42 }; System.Console.Write($""{c.Property}""); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void InitOnlyPropertyAssignmentAllowedInWithInitializer_Evaluation() { string source = @" record C { private int field; public int Property { get { return field; } init { field = value; System.Console.Write(""set ""); } } public C Clone() { System.Console.Write(""clone ""); return this; } } class Other { public static void Main() { var c = new C() with { Property = 42 }; System.Console.Write($""{c.Property}""); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "clone set 42"); } [Fact] public void EvaluationInitOnlySetter() { string source = @" public class C { public int Property { init { System.Console.Write(value + "" ""); } } public int Property2 { init { System.Console.Write(value); } } C() { System.Console.Write(""Main ""); } static void Main() { _ = new C() { Property = 42, Property2 = 43}; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Main 42 43"); } [Theory] [InlineData(true)] [InlineData(false)] public void EvaluationInitOnlySetter_OverrideAutoProp(bool emitImage) { string parent = @" public class Base { public virtual int Property { get; init; } }"; string source = @" public class C : Base { int field; public override int Property { get { System.Console.Write(""get:"" + field + "" ""); return field; } init { field = value; System.Console.Write(""set:"" + value + "" ""); } } public C() { System.Console.Write(""Main ""); } }"; string main = @" public class D { static void Main() { var c = new C() { Property = 42 }; _ = c.Property; } } "; var libComp = CreateCompilation(new[] { parent, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); var comp = CreateCompilation(new[] { source, main }, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "Main set:42 get:42"); libComp = CreateCompilation(new[] { parent, source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp = CreateCompilation(new[] { main }, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "Main set:42 get:42"); } [Theory] [InlineData(true)] [InlineData(false)] public void EvaluationInitOnlySetter_AutoProp(bool emitImage) { string source = @" public class C { public int Property { get; init; } public C() { System.Console.Write(""Main ""); } }"; string main = @" public class D { static void Main() { var c = new C() { Property = 42 }; System.Console.Write($""{c.Property}""); } } "; var libComp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); var comp = CreateCompilation(new[] { main }, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "Main 42"); } [Theory] [InlineData(true)] [InlineData(false)] public void EvaluationInitOnlySetter_Implementation(bool emitImage) { string parent = @" public interface I { int Property { get; init; } }"; string source = @" public class C : I { int field; public int Property { get { System.Console.Write(""get:"" + field + "" ""); return field; } init { field = value; System.Console.Write(""set:"" + value + "" ""); } } public C() { System.Console.Write(""Main ""); } }"; string main = @" public class D { static void Main() { M<C>(); } static void M<T>() where T : I, new() { var t = new T() { Property = 42 }; _ = t.Property; } } "; var libComp = CreateCompilation(new[] { parent, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); var comp = CreateCompilation(new[] { source, main }, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "Main set:42 get:42"); libComp = CreateCompilation(new[] { parent, source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp = CreateCompilation(new[] { main }, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "Main set:42 get:42"); } [Fact] public void DisallowedOnStaticMembers() { string source = @" public class C { public static string Property { get; init; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,42): error CS8806: The 'init' accessor is not valid on static members // public static string Property { get; init; } Diagnostic(ErrorCode.ERR_BadInitAccessor, "init").WithLocation(4, 42) ); var property = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().GetMethod.IsInitOnly); Assert.False(property.SetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void DisallowedOnOtherInstances() { string source = @" public class C { public string Property { get; init; } public C c; public C() { c.Property = null; // 1 } public string InitOnlyProperty { init { c.Property = null; // 2 } } } public class Derived : C { Derived() { c.Property = null; // 3 } public string InitOnlyProperty2 { init { c.Property = null; // 4 } } } public class Caller { void M(C c) { _ = new C() { Property = (c.Property = null) // 5 }; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (9,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(9, 9), // (16,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(16, 13), // (24,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(24, 9), // (31,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(31, 13), // (41,18): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // (c.Property = null) // 5 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(41, 18) ); } [Fact] public void DeconstructionAssignmentDisallowed() { string source = @" public class C { public string Property { get; init; } void M() { (Property, (Property, Property)) = (null, (null, null)); // 1, 2, 3 } C() { (Property, (Property, Property)) = (null, (null, null)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,10): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // (Property, (Property, Property)) = (null, (null, null)); // 1, 2, 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 10), // (8,21): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // (Property, (Property, Property)) = (null, (null, null)); // 1, 2, 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 21), // (8,31): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // (Property, (Property, Property)) = (null, (null, null)); // 1, 2, 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 31) ); } [Fact] public void OutParameterAssignmentDisallowed() { string source = @" public class C { public string Property { get; init; } void M() { M2(out Property); // 1 } void M2(out string s) => throw null; } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,16): error CS0206: A property or indexer may not be passed as an out or ref parameter // M2(out Property); // 1 Diagnostic(ErrorCode.ERR_RefProperty, "Property").WithArguments("C.Property").WithLocation(8, 16) ); } [Fact] public void CompoundAssignmentDisallowed() { string source = @" public class C { public int Property { get; init; } void M() { Property += 42; // 1 } C() { Property += 42; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property += 42; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9) ); } [Fact] public void CompoundAssignmentDisallowed_OrAssignment() { string source = @" public class C { public bool Property { get; init; } void M() { Property |= true; // 1 } C() { Property |= true; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property |= true; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9) ); } [Fact] public void CompoundAssignmentDisallowed_NullCoalescingAssignment() { string source = @" public class C { public string Property { get; init; } void M() { Property ??= null; // 1 } C() { Property ??= null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property ??= null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9) ); } [Fact] public void CompoundAssignmentDisallowed_Increment() { string source = @" public class C { public int Property { get; init; } void M() { Property++; // 1 } C() { Property++; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property++; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9) ); } [Fact] public void RefProperty() { string source = @" public class C { ref int Property1 { get; init; } ref int Property2 { init; } ref int Property3 { get => throw null; init => throw null; } ref int Property4 { init => throw null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,13): error CS8145: Auto-implemented properties cannot return by reference // ref int Property1 { get; init; } Diagnostic(ErrorCode.ERR_AutoPropertyCannotBeRefReturning, "Property1").WithArguments("C.Property1").WithLocation(4, 13), // (4,30): error CS8147: Properties which return by reference cannot have set accessors // ref int Property1 { get; init; } Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "init").WithArguments("C.Property1.init").WithLocation(4, 30), // (5,13): error CS8146: Properties which return by reference must have a get accessor // ref int Property2 { init; } Diagnostic(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, "Property2").WithArguments("C.Property2").WithLocation(5, 13), // (6,44): error CS8147: Properties which return by reference cannot have set accessors // ref int Property3 { get => throw null; init => throw null; } Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "init").WithArguments("C.Property3.init").WithLocation(6, 44), // (7,13): error CS8146: Properties which return by reference must have a get accessor // ref int Property4 { init => throw null; } Diagnostic(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, "Property4").WithArguments("C.Property4").WithLocation(7, 13) ); } [Fact] public void VerifyPESymbols_Property() { string source = @" public class C { public string Property { get; init; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); // PE verification fails: [ : C::set_Property] Cannot change initonly field outside its .ctor. CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var c = (NamedTypeSymbol)m.GlobalNamespace.GetMember("C"); var property = (PropertySymbol)c.GetMembers("Property").Single(); Assert.Equal("System.String C.Property { get; init; }", property.ToTestDisplayString()); Assert.Equal(0, property.CustomModifierCount()); var propertyAttributes = property.GetAttributes().Select(a => a.ToString()); AssertEx.Empty(propertyAttributes); var getter = property.GetMethod; Assert.Empty(property.GetMethod.ReturnTypeWithAnnotations.CustomModifiers); Assert.False(getter.IsInitOnly); Assert.False(getter.GetPublicSymbol().IsInitOnly); var getterAttributes = getter.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(getterAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute" }, getterAttributes); } var setter = property.SetMethod; Assert.True(setter.IsInitOnly); Assert.True(setter.GetPublicSymbol().IsInitOnly); var setterAttributes = property.SetMethod.GetAttributes().Select(a => a.ToString()); var modifier = property.SetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single(); Assert.Equal("System.Runtime.CompilerServices.IsExternalInit", modifier.Modifier.ToTestDisplayString()); Assert.False(modifier.IsOptional); if (isSource) { AssertEx.Empty(setterAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute" }, setterAttributes); } var backingField = (FieldSymbol)c.GetMembers("<Property>k__BackingField").Single(); var backingFieldAttributes = backingField.GetAttributes().Select(a => a.ToString()); Assert.True(backingField.IsReadOnly); if (isSource) { AssertEx.Empty(backingFieldAttributes); } else { AssertEx.Equal( new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute", "System.Diagnostics.DebuggerBrowsableAttribute(System.Diagnostics.DebuggerBrowsableState.Never)" }, backingFieldAttributes); var peBackingField = (PEFieldSymbol)backingField; Assert.Equal(System.Reflection.FieldAttributes.InitOnly | System.Reflection.FieldAttributes.Private, peBackingField.Flags); } } } [Theory] [InlineData(true)] [InlineData(false)] public void AssignmentDisallowed_PE(bool emitImage) { string lib_cs = @" public class C { public string Property { get; init; } } "; var libComp = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); libComp.VerifyDiagnostics(); string source = @" public class Other { public C c; void M() { c.Property = null; // 1 } public Other() { c.Property = null; // 2 } public string InitOnlyProperty { get { c.Property = null; // 3 return null; } init { c.Property = null; // 4 } } public string RegularProperty { get { c.Property = null; // 5 return null; } set { c.Property = null; // 6 } } } class Derived : C { } class Derived2 : Derived { void M() { Property = null; // 7 base.Property = null; // 8 } Derived2() { Property = null; base.Property = null; } public string InitOnlyProperty2 { get { Property = null; // 9 base.Property = null; // 10 return null; } init { Property = null; base.Property = null; } } public string RegularProperty2 { get { Property = null; // 11 base.Property = null; // 12 return null; } set { Property = null; // 13 base.Property = null; // 14 } } } "; var comp = CreateCompilation(source, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(8, 9), // (13,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(13, 9), // (20,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(20, 13), // (25,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(25, 13), // (33,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 5 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(33, 13), // (38,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 6 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(38, 13), // (51,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 7 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(51, 9), // (52,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // base.Property = null; // 8 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "base.Property").WithArguments("C.Property").WithLocation(52, 9), // (65,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 9 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(65, 13), // (66,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // base.Property = null; // 10 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "base.Property").WithArguments("C.Property").WithLocation(66, 13), // (80,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 11 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(80, 13), // (81,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // base.Property = null; // 12 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "base.Property").WithArguments("C.Property").WithLocation(81, 13), // (86,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 13 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(86, 13), // (87,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // base.Property = null; // 14 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "base.Property").WithArguments("C.Property").WithLocation(87, 13) ); } [Fact, WorkItem(50053, "https://github.com/dotnet/roslyn/issues/50053")] public void PrivatelyImplementingInitOnlyProperty_ReferenceConversion() { string source = @" var x = new DerivedType() { SomethingElse = 42 }; System.Console.Write(x.SomethingElse); public interface ISomething { int Property { get; init; } } public record BaseType : ISomething { int ISomething.Property { get; init; } } public record DerivedType : BaseType { public int SomethingElse { get => ((ISomething)this).Property; init => ((ISomething)this).Property = value; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (13,17): error CS8852: Init-only property or indexer 'ISomething.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // init => ((ISomething)this).Property = value; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "((ISomething)this).Property").WithArguments("ISomething.Property").WithLocation(13, 17) ); } [Fact, WorkItem(50053, "https://github.com/dotnet/roslyn/issues/50053")] public void PrivatelyImplementingInitOnlyProperty_BoxingConversion() { string source = @" var x = new Type() { SomethingElse = 42 }; public interface ISomething { int Property { get; init; } } public struct Type : ISomething { int ISomething.Property { get; init; } public int SomethingElse { get => throw null; init => ((ISomething)this).Property = value; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (13,17): error CS8852: Init-only property or indexer 'ISomething.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // init => ((ISomething)this).Property = value; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "((ISomething)this).Property").WithArguments("ISomething.Property").WithLocation(13, 17) ); } [Fact] public void OverridingInitOnlyProperty() { string source = @" public class Base { public virtual string Property { get; init; } } public class DerivedWithInit : Base { public override string Property { get; init; } } public class DerivedWithoutInit : Base { public override string Property { get; set; } // 1 } public class DerivedWithInitSetterOnly : Base { public override string Property { init { } } } public class DerivedWithoutInitSetterOnly : Base { public override string Property { set { } } // 2 } public class DerivedGetterOnly : Base { public override string Property { get => null; } } public class DerivedDerivedWithInit : DerivedGetterOnly { public override string Property { init { } } } public class DerivedDerivedWithoutInit : DerivedGetterOnly { public override string Property { set { } } // 3 } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (13,28): error CS8803: 'DerivedWithoutInit.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { get; set; } // 1 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithoutInit.Property", "Base.Property").WithLocation(13, 28), // (22,28): error CS8803: 'DerivedWithoutInitSetterOnly.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { set { } } // 2 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithoutInitSetterOnly.Property", "Base.Property").WithLocation(22, 28), // (35,28): error CS8803: 'DerivedDerivedWithoutInit.Property' must match by init-only of overridden member 'DerivedGetterOnly.Property' // public override string Property { set { } } // 3 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedDerivedWithoutInit.Property", "DerivedGetterOnly.Property").WithLocation(35, 28) ); } [Theory] [InlineData(true)] [InlineData(false)] public void OverridingInitOnlyProperty_Metadata(bool emitAsImage) { string lib_cs = @" public class Base { public virtual string Property { get; init; } }"; var libComp = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); libComp.VerifyDiagnostics(); string source = @" public class DerivedWithInit : Base { public override string Property { get; init; } } public class DerivedWithoutInit : Base { public override string Property { get; set; } // 1 } public class DerivedWithInitSetterOnly : Base { public override string Property { init { } } } public class DerivedWithoutInitSetterOnly : Base { public override string Property { set { } } // 2 } public class DerivedGetterOnly : Base { public override string Property { get => null; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { emitAsImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (8,28): error CS8803: 'DerivedWithoutInit.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { get; set; } // 1 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithoutInit.Property", "Base.Property").WithLocation(8, 28), // (16,28): error CS8803: 'DerivedWithoutInitSetterOnly.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { set { } } // 2 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithoutInitSetterOnly.Property", "Base.Property").WithLocation(16, 28) ); } [Fact] public void OverridingRegularProperty() { string source = @" public class Base { public virtual string Property { get; set; } } public class DerivedWithInit : Base { public override string Property { get; init; } // 1 } public class DerivedWithoutInit : Base { public override string Property { get; set; } } public class DerivedWithInitSetterOnly : Base { public override string Property { init { } } // 2 } public class DerivedWithoutInitSetterOnly : Base { public override string Property { set { } } } public class DerivedGetterOnly : Base { public override string Property { get => null; } } public class DerivedDerivedWithInit : DerivedGetterOnly { public override string Property { init { } } // 3 } public class DerivedDerivedWithoutInit : DerivedGetterOnly { public override string Property { set { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (9,28): error CS8803: 'DerivedWithInit.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { get; init; } // 1 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithInit.Property", "Base.Property").WithLocation(9, 28), // (18,28): error CS8803: 'DerivedWithInitSetterOnly.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { init { } } // 2 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithInitSetterOnly.Property", "Base.Property").WithLocation(18, 28), // (31,28): error CS8803: 'DerivedDerivedWithInit.Property' must match by init-only of overridden member 'DerivedGetterOnly.Property' // public override string Property { init { } } // 3 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedDerivedWithInit.Property", "DerivedGetterOnly.Property").WithLocation(31, 28) ); } [Fact] public void OverridingGetterOnlyProperty() { string source = @" public class Base { public virtual string Property { get => null; } } public class DerivedWithInit : Base { public override string Property { get; init; } // 1 } public class DerivedWithoutInit : Base { public override string Property { get; set; } // 2 } public class DerivedWithInitSetterOnly : Base { public override string Property { init { } } // 3 } public class DerivedWithoutInitSetterOnly : Base { public override string Property { set { } } // 4 } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,44): error CS0546: 'DerivedWithInit.Property.init': cannot override because 'Base.Property' does not have an overridable set accessor // public override string Property { get; init; } // 1 Diagnostic(ErrorCode.ERR_NoSetToOverride, "init").WithArguments("DerivedWithInit.Property.init", "Base.Property").WithLocation(8, 44), // (12,44): error CS0546: 'DerivedWithoutInit.Property.set': cannot override because 'Base.Property' does not have an overridable set accessor // public override string Property { get; set; } // 2 Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("DerivedWithoutInit.Property.set", "Base.Property").WithLocation(12, 44), // (16,39): error CS0546: 'DerivedWithInitSetterOnly.Property.init': cannot override because 'Base.Property' does not have an overridable set accessor // public override string Property { init { } } // 3 Diagnostic(ErrorCode.ERR_NoSetToOverride, "init").WithArguments("DerivedWithInitSetterOnly.Property.init", "Base.Property").WithLocation(16, 39), // (20,39): error CS0546: 'DerivedWithoutInitSetterOnly.Property.set': cannot override because 'Base.Property' does not have an overridable set accessor // public override string Property { set { } } // 4 Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("DerivedWithoutInitSetterOnly.Property.set", "Base.Property").WithLocation(20, 39) ); } [Fact] public void OverridingSetterOnlyProperty() { string source = @" public class Base { public virtual string Property { set { } } } public class DerivedWithInit : Base { public override string Property { get; init; } // 1, 2 } public class DerivedWithoutInit : Base { public override string Property { get; set; } // 3 } public class DerivedWithInitSetterOnly : Base { public override string Property { init { } } // 4 } public class DerivedWithoutInitGetterOnly : Base { public override string Property { get => null; } // 5 } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,28): error CS8803: 'DerivedWithInit.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { get; init; } // 1, 2 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithInit.Property", "Base.Property").WithLocation(8, 28), // (8,39): error CS0545: 'DerivedWithInit.Property.get': cannot override because 'Base.Property' does not have an overridable get accessor // public override string Property { get; init; } // 1, 2 Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("DerivedWithInit.Property.get", "Base.Property").WithLocation(8, 39), // (12,39): error CS0545: 'DerivedWithoutInit.Property.get': cannot override because 'Base.Property' does not have an overridable get accessor // public override string Property { get; set; } // 3 Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("DerivedWithoutInit.Property.get", "Base.Property").WithLocation(12, 39), // (16,28): error CS8803: 'DerivedWithInitSetterOnly.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { init { } } // 4 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithInitSetterOnly.Property", "Base.Property").WithLocation(16, 28), // (20,39): error CS0545: 'DerivedWithoutInitGetterOnly.Property.get': cannot override because 'Base.Property' does not have an overridable get accessor // public override string Property { get => null; } // 5 Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("DerivedWithoutInitGetterOnly.Property.get", "Base.Property").WithLocation(20, 39) ); } [Fact] public void ImplementingInitOnlyProperty() { string source = @" public interface I { string Property { get; init; } } public class DerivedWithInit : I { public string Property { get; init; } } public class DerivedWithoutInit : I // 1 { public string Property { get; set; } } public class DerivedWithInitSetterOnly : I // 2 { public string Property { init { } } } public class DerivedWithoutInitGetterOnly : I // 3 { public string Property { get => null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (10,35): error CS8804: 'DerivedWithoutInit' does not implement interface member 'I.Property.init'. 'DerivedWithoutInit.Property.set' cannot implement 'I.Property.init'. // public class DerivedWithoutInit : I // 1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("DerivedWithoutInit", "I.Property.init", "DerivedWithoutInit.Property.set").WithLocation(10, 35), // (14,42): error CS0535: 'DerivedWithInitSetterOnly' does not implement interface member 'I.Property.get' // public class DerivedWithInitSetterOnly : I // 2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("DerivedWithInitSetterOnly", "I.Property.get").WithLocation(14, 42), // (18,45): error CS0535: 'DerivedWithoutInitGetterOnly' does not implement interface member 'I.Property.init' // public class DerivedWithoutInitGetterOnly : I // 3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("DerivedWithoutInitGetterOnly", "I.Property.init").WithLocation(18, 45) ); } [Fact] public void ImplementingSetterOnlyProperty() { string source = @" public interface I { string Property { set; } } public class DerivedWithInit : I // 1 { public string Property { get; init; } } public class DerivedWithoutInit : I { public string Property { get; set; } } public class DerivedWithInitSetterOnly : I // 2 { public string Property { init { } } } public class DerivedWithoutInitGetterOnly : I // 3 { public string Property { get => null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,32): error CS8804: 'DerivedWithInit' does not implement interface member 'I.Property.set'. 'DerivedWithInit.Property.init' cannot implement 'I.Property.set'. // public class DerivedWithInit : I // 1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("DerivedWithInit", "I.Property.set", "DerivedWithInit.Property.init").WithLocation(6, 32), // (14,42): error CS8804: 'DerivedWithInitSetterOnly' does not implement interface member 'I.Property.set'. 'DerivedWithInitSetterOnly.Property.init' cannot implement 'I.Property.set'. // public class DerivedWithInitSetterOnly : I // 2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("DerivedWithInitSetterOnly", "I.Property.set", "DerivedWithInitSetterOnly.Property.init").WithLocation(14, 42), // (18,45): error CS0535: 'DerivedWithoutInitGetterOnly' does not implement interface member 'I.Property.set' // public class DerivedWithoutInitGetterOnly : I // 3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("DerivedWithoutInitGetterOnly", "I.Property.set").WithLocation(18, 45) ); } [Fact] public void ObjectCreationOnInterface() { string source = @" public interface I { string Property { set; } string InitProperty { init; } } public class C { void M<T>() where T: I, new() { _ = new T() { Property = null, InitProperty = null }; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void HidingInitOnlySetterOnlyProperty() { string source = @" public class Base { public string Property { init { } } } public class Derived : Base { public string Property { init { } } // 1 } public class DerivedWithNew : Base { public new string Property { init { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,19): warning CS0108: 'Derived.Property' hides inherited member 'Base.Property'. Use the new keyword if hiding was intended. // public string Property { init { } } // 1 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("Derived.Property", "Base.Property").WithLocation(8, 19) ); } [Theory] [InlineData(true)] [InlineData(false)] public void ImplementingSetterOnlyProperty_Metadata(bool emitAsImage) { string lib_cs = @" public interface I { string Property { set; } }"; var libComp = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); libComp.VerifyEmitDiagnostics(); string source = @" public class DerivedWithInit : I // 1 { public string Property { get; init; } } public class DerivedWithoutInit : I { public string Property { get; set; } } public class DerivedWithInitSetterOnly : I // 2 { public string Property { init { } } } public class DerivedWithoutInitGetterOnly : I // 3 { public string Property { get => null; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { emitAsImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (2,32): error CS8804: 'DerivedWithInit' does not implement interface member 'I.Property.set'. 'DerivedWithInit.Property.init' cannot implement 'I.Property.set'. // public class DerivedWithInit : I // 1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("DerivedWithInit", "I.Property.set", "DerivedWithInit.Property.init").WithLocation(2, 32), // (10,42): error CS8804: 'DerivedWithInitSetterOnly' does not implement interface member 'I.Property.set'. 'DerivedWithInitSetterOnly.Property.init' cannot implement 'I.Property.set'. // public class DerivedWithInitSetterOnly : I // 2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("DerivedWithInitSetterOnly", "I.Property.set", "DerivedWithInitSetterOnly.Property.init").WithLocation(10, 42), // (14,45): error CS0535: 'DerivedWithoutInitGetterOnly' does not implement interface member 'I.Property.set' // public class DerivedWithoutInitGetterOnly : I // 3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("DerivedWithoutInitGetterOnly", "I.Property.set").WithLocation(14, 45) ); } [Fact] public void ImplementingSetterOnlyProperty_Explicitly() { string source = @" public interface I { string Property { set; } } public class DerivedWithInit : I { string I.Property { init { } } // 1 } public class DerivedWithInitAndGetter : I { string I.Property { get; init; } // 2, 3 } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,25): error CS8805: Accessors 'DerivedWithInit.I.Property.init' and 'I.Property.set' should both be init-only or neither // string I.Property { init { } } // 1 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "init").WithArguments("DerivedWithInit.I.Property.init", "I.Property.set").WithLocation(8, 25), // (12,25): error CS0550: 'DerivedWithInitAndGetter.I.Property.get' adds an accessor not found in interface member 'I.Property' // string I.Property { get; init; } // 2, 3 Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("DerivedWithInitAndGetter.I.Property.get", "I.Property").WithLocation(12, 25), // (12,30): error CS8805: Accessors 'DerivedWithInitAndGetter.I.Property.init' and 'I.Property.set' should both be init-only or neither // string I.Property { get; init; } // 2, 3 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "init").WithArguments("DerivedWithInitAndGetter.I.Property.init", "I.Property.set").WithLocation(12, 30) ); } [Fact] public void ImplementingSetterOnlyInitOnlyProperty_Explicitly() { string source = @" public interface I { string Property { init; } } public class DerivedWithoutInit : I { string I.Property { set { } } // 1 } public class DerivedWithInit : I { string I.Property { init { } } } public class DerivedWithInitAndGetter : I { string I.Property { get; init; } // 2 } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,25): error CS8805: Accessors 'DerivedWithoutInit.I.Property.set' and 'I.Property.init' should both be init-only or neither // string I.Property { set { } } // 1 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "set").WithArguments("DerivedWithoutInit.I.Property.set", "I.Property.init").WithLocation(8, 25), // (16,25): error CS0550: 'DerivedWithInitAndGetter.I.Property.get' adds an accessor not found in interface member 'I.Property' // string I.Property { get; init; } // 2 Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("DerivedWithInitAndGetter.I.Property.get", "I.Property").WithLocation(16, 25) ); } [Theory] [InlineData(true)] [InlineData(false)] public void ImplementingSetterOnlyInitOnlyProperty_Metadata_Explicitly(bool emitAsImage) { string lib_cs = @" public interface I { string Property { init; } }"; var libComp = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); libComp.VerifyDiagnostics(); string source = @" public class DerivedWithoutInit : I { string I.Property { set { } } // 1 } public class DerivedWithInit : I { string I.Property { init { } } } public class DerivedGetterOnly : I // 2 { string I.Property { get => null; } // 3, 4 } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { emitAsImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (4,25): error CS8805: Accessors 'DerivedWithoutInit.I.Property.set' and 'I.Property.init' should both be init-only or neither // string I.Property { set { } } // 1 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "set").WithArguments("DerivedWithoutInit.I.Property.set", "I.Property.init").WithLocation(4, 25), // (10,34): error CS0535: 'DerivedGetterOnly' does not implement interface member 'I.Property.init' // public class DerivedGetterOnly : I // 2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("DerivedGetterOnly", "I.Property.init").WithLocation(10, 34), // (12,14): error CS0551: Explicit interface implementation 'DerivedGetterOnly.I.Property' is missing accessor 'I.Property.init' // string I.Property { get => null; } // 3, 4 Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "Property").WithArguments("DerivedGetterOnly.I.Property", "I.Property.init").WithLocation(12, 14), // (12,25): error CS0550: 'DerivedGetterOnly.I.Property.get' adds an accessor not found in interface member 'I.Property' // string I.Property { get => null; } // 3, 4 Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("DerivedGetterOnly.I.Property.get", "I.Property").WithLocation(12, 25) ); } [Fact] public void DIM_TwoInitOnlySetters() { string source = @" public interface I1 { string Property { init; } } public interface I2 { string Property { init; } } public interface IWithoutInit : I1, I2 { string Property { set; } // 1 } public interface IWithInit : I1, I2 { string Property { init; } // 2 } public interface IWithInitWithNew : I1, I2 { new string Property { init; } } public interface IWithInitWithDefaultImplementation : I1, I2 { string Property { init { } } // 3 } public interface IWithInitWithExplicitImplementation : I1, I2 { string I1.Property { init { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular9); Assert.True(comp.Assembly.RuntimeSupportsDefaultInterfaceImplementation); comp.VerifyEmitDiagnostics( // (12,12): warning CS0108: 'IWithoutInit.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { set; } // 1 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithoutInit.Property", "I1.Property").WithLocation(12, 12), // (16,12): warning CS0108: 'IWithInit.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { init; } // 2 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithInit.Property", "I1.Property").WithLocation(16, 12), // (24,12): warning CS0108: 'IWithInitWithDefaultImplementation.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { init { } } // 3 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithInitWithDefaultImplementation.Property", "I1.Property").WithLocation(24, 12) ); } [Fact] public void DIM_OneInitOnlySetter() { string source = @" public interface I1 { string Property { init; } } public interface I2 { string Property { set; } } public interface IWithoutInit : I1, I2 { string Property { set; } // 1 } public interface IWithInit : I1, I2 { string Property { init; } // 2 } public interface IWithInitWithNew : I1, I2 { new string Property { init; } } public interface IWithoutInitWithNew : I1, I2 { new string Property { set; } } public interface IWithInitWithImplementation : I1, I2 { string Property { init { } } // 3 } public interface IWithInitWithExplicitImplementationOfI1 : I1, I2 { string I1.Property { init { } } } public interface IWithInitWithExplicitImplementationOfI2 : I1, I2 { string I2.Property { init { } } // 4 } public interface IWithoutInitWithExplicitImplementationOfI1 : I1, I2 { string I1.Property { set { } } // 5 } public interface IWithoutInitWithExplicitImplementationOfI2 : I1, I2 { string I2.Property { set { } } } public interface IWithoutInitWithExplicitImplementationOfBoth : I1, I2 { string I1.Property { init { } } string I2.Property { set { } } } public class CWithExplicitImplementation : I1, I2 { string I1.Property { init { } } string I2.Property { set { } } } public class CWithImplementationWithInitOnly : I1, I2 // 6 { public string Property { init { } } } public class CWithImplementationWithoutInitOnly : I1, I2 // 7 { public string Property { set { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular9); Assert.True(comp.Assembly.RuntimeSupportsDefaultInterfaceImplementation); comp.VerifyEmitDiagnostics( // (13,12): warning CS0108: 'IWithoutInit.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { set; } // 1 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithoutInit.Property", "I1.Property").WithLocation(13, 12), // (17,12): warning CS0108: 'IWithInit.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { init; } // 2 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithInit.Property", "I1.Property").WithLocation(17, 12), // (31,12): warning CS0108: 'IWithInitWithImplementation.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { init { } } // 3 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithInitWithImplementation.Property", "I1.Property").WithLocation(31, 12), // (40,26): error CS8805: Accessors 'IWithInitWithExplicitImplementationOfI2.I2.Property.init' and 'I2.Property.set' should both be init-only or neither // string I2.Property { init { } } // 4 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "init").WithArguments("IWithInitWithExplicitImplementationOfI2.I2.Property.init", "I2.Property.set").WithLocation(40, 26), // (45,26): error CS8805: Accessors 'IWithoutInitWithExplicitImplementationOfI1.I1.Property.set' and 'I1.Property.init' should both be init-only or neither // string I1.Property { set { } } // 5 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "set").WithArguments("IWithoutInitWithExplicitImplementationOfI1.I1.Property.set", "I1.Property.init").WithLocation(45, 26), // (62,52): error CS8804: 'CWithImplementationWithInitOnly' does not implement interface member 'I2.Property.set'. 'CWithImplementationWithInitOnly.Property.init' cannot implement 'I2.Property.set'. // public class CWithImplementationWithInitOnly : I1, I2 // 6 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I2").WithArguments("CWithImplementationWithInitOnly", "I2.Property.set", "CWithImplementationWithInitOnly.Property.init").WithLocation(62, 52), // (66,51): error CS8804: 'CWithImplementationWithoutInitOnly' does not implement interface member 'I1.Property.init'. 'CWithImplementationWithoutInitOnly.Property.set' cannot implement 'I1.Property.init'. // public class CWithImplementationWithoutInitOnly : I1, I2 // 7 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I1").WithArguments("CWithImplementationWithoutInitOnly", "I1.Property.init", "CWithImplementationWithoutInitOnly.Property.set").WithLocation(66, 51) ); } [Fact] public void EventWithInitOnly() { string source = @" public class C { public event System.Action Event { init { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,32): error CS0065: 'C.Event': event property must have both add and remove accessors // public event System.Action Event Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "Event").WithArguments("C.Event").WithLocation(4, 32), // (6,9): error CS1055: An add or remove accessor expected // init { } Diagnostic(ErrorCode.ERR_AddOrRemoveExpected, "init").WithLocation(6, 9) ); var members = ((NamedTypeSymbol)comp.GlobalNamespace.GetMember("C")).GetMembers(); AssertEx.SetEqual(members.ToTestDisplayStrings(), new[] { "event System.Action C.Event", "C..ctor()" }); } [Fact] public void EventAccessorsAreNotInitOnly() { string source = @" public class C { public event System.Action Event { add { } remove { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var eventSymbol = comp.GlobalNamespace.GetMember<EventSymbol>("C.Event"); Assert.False(eventSymbol.AddMethod.IsInitOnly); Assert.False(eventSymbol.GetPublicSymbol().AddMethod.IsInitOnly); Assert.False(eventSymbol.RemoveMethod.IsInitOnly); Assert.False(eventSymbol.GetPublicSymbol().RemoveMethod.IsInitOnly); } [Fact] public void ConstructorAndDestructorAreNotInitOnly() { string source = @" public class C { public C() { } ~C() { } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var constructor = comp.GlobalNamespace.GetMember<SourceConstructorSymbol>("C..ctor"); Assert.False(constructor.IsInitOnly); Assert.False(constructor.GetPublicSymbol().IsInitOnly); var destructor = comp.GlobalNamespace.GetMember<SourceDestructorSymbol>("C.Finalize"); Assert.False(destructor.IsInitOnly); Assert.False(destructor.GetPublicSymbol().IsInitOnly); } [Fact] public void OperatorsAreNotInitOnly() { string source = @" public class C { public static implicit operator int(C c) => throw null; public static bool operator +(C c1, C c2) => throw null; } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var conversion = comp.GlobalNamespace.GetMember<SourceUserDefinedConversionSymbol>("C.op_Implicit"); Assert.False(conversion.IsInitOnly); Assert.False(conversion.GetPublicSymbol().IsInitOnly); var addition = comp.GlobalNamespace.GetMember<SourceUserDefinedOperatorSymbol>("C.op_Addition"); Assert.False(addition.IsInitOnly); Assert.False(addition.GetPublicSymbol().IsInitOnly); } [Fact] public void ConstructedMethodsAreNotInitOnly() { string source = @" public class C { void M<T>() { M<string>(); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var root = tree.GetCompilationUnitRoot(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: true); var invocation = root.DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var method = (IMethodSymbol)model.GetSymbolInfo(invocation).Symbol; Assert.Equal("void C.M<System.String>()", method.ToTestDisplayString()); Assert.False(method.IsInitOnly); } [Fact] public void InitOnlyOnMembersOfRecords() { string source = @" public record C(int i) { void M() { } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var cMembers = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(); AssertEx.SetEqual(new[] { "C C." + WellKnownMemberNames.CloneMethodName + "()", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "C..ctor(System.Int32 i)", "System.Int32 C.<i>k__BackingField", "System.Int32 C.i.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.i.init", "System.Int32 C.i { get; init; }", "void C.M()", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C..ctor(C original)", "void C.Deconstruct(out System.Int32 i)", }, cMembers.ToTestDisplayStrings()); foreach (var member in cMembers) { if (member is MethodSymbol method) { bool isSetter = method.MethodKind == MethodKind.PropertySet; Assert.Equal(isSetter, method.IsInitOnly); Assert.Equal(isSetter, method.GetPublicSymbol().IsInitOnly); } } } [Fact] public void IndexerWithInitOnly() { string source = @" public class C { public string this[int i] { init { } } public C() { this[42] = null; } public void M1() { this[43] = null; // 1 } } public class Derived : C { public Derived() { this[44] = null; } public void M2() { this[45] = null; // 2 } } public class D { void M3(C c2) { _ = new C() { [46] = null }; c2[47] = null; // 3 } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (14,9): error CS8802: Init-only property or indexer 'C.this[int]' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // this[43] = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "this[43]").WithArguments("C.this[int]").WithLocation(14, 9), // (25,9): error CS8802: Init-only property or indexer 'C.this[int]' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // this[45] = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "this[45]").WithArguments("C.this[int]").WithLocation(25, 9), // (33,9): error CS8802: Init-only property or indexer 'C.this[int]' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c2[47] = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c2[47]").WithArguments("C.this[int]").WithLocation(33, 9) ); } [Fact] public void ReadonlyFields() { string source = @" public class C { public readonly string field; public C() { field = null; } public void M1() { field = null; // 1 _ = new C() { field = null }; // 2 } public int InitOnlyProperty1 { init { field = null; } } public int RegularProperty { get { field = null; // 3 throw null; } set { field = null; // 4 } } } public class Derived : C { public Derived() { field = null; // 5 } public void M2() { field = null; // 6 } public int InitOnlyProperty2 { init { field = null; // 7 } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (11,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the class in which the field is defined or a variable initializer)) // field = null; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(11, 9), // (12,23): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // _ = new C() { field = null }; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(12, 23), // (25,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(25, 13), // (30,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(30, 13), // (38,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 5 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(38, 9), // (42,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 6 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(42, 9), // (48,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 7 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(48, 13) ); } [Fact] public void ReadonlyFields_Evaluation() { string source = @" public class C { public readonly int field; public static void Main() { var c1 = new C(); System.Console.Write($""{c1.field} ""); var c2 = new C() { Property = 43 }; System.Console.Write($""{c2.field}""); } public C() { field = 42; } public int Property { init { field = value; } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); // [ : C::set_Property] Cannot change initonly field outside its .ctor. CompileAndVerify(comp, expectedOutput: "42 43", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails); } [Fact] public void ReadonlyFields_TypesDifferingNullability() { string source = @" public class C { public static void Main() { System.Console.Write(C1<int>.F1.content); System.Console.Write("" ""); System.Console.Write(C2<int>.F1.content); } } public struct Container { public int content; } class C1<T> { public static readonly Container F1; static C1() { C1<T>.F1.content = 2; } } #nullable enable class C2<T> { public static readonly Container F1; static C2() { C2<T>.F1.content = 3; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "2 3", verify: Verification.Skipped); // PEVerify bug // [ : C::Main][mdToken=0x6000004][offset 0x00000001] Cannot change initonly field outside its .ctor. v.VerifyIL("C.Main", @" { // Code size 45 (0x2d) .maxstack 1 IL_0000: nop IL_0001: ldsflda ""Container C1<int>.F1"" IL_0006: ldfld ""int Container.content"" IL_000b: call ""void System.Console.Write(int)"" IL_0010: nop IL_0011: ldstr "" "" IL_0016: call ""void System.Console.Write(string)"" IL_001b: nop IL_001c: ldsflda ""Container C2<int>.F1"" IL_0021: ldfld ""int Container.content"" IL_0026: call ""void System.Console.Write(int)"" IL_002b: nop IL_002c: ret } "); } [Fact] public void StaticReadonlyFieldInitializedByAnother() { string source = @" public class C { public static readonly int field; public static readonly int field2 = (field = 42); } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void ReadonlyFields_DisallowedOnOtherInstances() { string source = @" public class C { public readonly string field; public C c; public C() { c.field = null; // 1 } public string InitOnlyProperty { init { c.field = null; // 2 } } } public class Derived : C { Derived() { c.field = null; // 3 } public string InitOnlyProperty2 { init { c.field = null; // 4 } } } public class Caller { void M(C c) { _ = new C() { field = // 5 (c.field = null) // 6 }; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (9,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the class in which the field is defined or a variable initializer)) // c.field = null; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly, "c.field").WithLocation(9, 9), // (16,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // c.field = null; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly, "c.field").WithLocation(16, 13), // (24,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // c.field = null; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly, "c.field").WithLocation(24, 9), // (31,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // c.field = null; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly, "c.field").WithLocation(31, 13), // (40,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = // 5 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(40, 13), // (41,18): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // (c.field = null) // 6 Diagnostic(ErrorCode.ERR_AssgReadonly, "c.field").WithLocation(41, 18) ); } [Fact, WorkItem(45657, "https://github.com/dotnet/roslyn/issues/45657")] public void ReadonlyFieldsMembers() { string source = @" public struct Container { public string content; } public class C { public readonly Container field; public C() { field.content = null; } public void M1() { field.content = null; // 1 } public int InitOnlyProperty1 { init { field.content = null; } } public int RegularProperty { get { field.content = null; // 2 throw null; } set { field.content = null; // 3 } } } public class Derived : C { public Derived() { field.content = null; // 4 } public void M2() { field.content = null; // 5 } public int InitOnlyProperty2 { init { field.content = null; // 6 } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (15,9): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(15, 9), // (28,13): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(28, 13), // (33,13): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(33, 13), // (41,9): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(41, 9), // (45,9): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 5 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(45, 9), // (51,13): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 6 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(51, 13) ); } [Fact, WorkItem(45657, "https://github.com/dotnet/roslyn/issues/45657")] public void ReadonlyFieldsMembers_Evaluation() { string source = @" public struct Container { public int content; } public class C { public readonly Container field; public int InitOnlyProperty1 { init { field.content = value; System.Console.Write(""RAN ""); } } public static void Main() { var c = new C() { InitOnlyProperty1 = 42 }; System.Console.Write(c.field.content); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN 42", verify: Verification.Skipped /* init-only */); } [Fact, WorkItem(45657, "https://github.com/dotnet/roslyn/issues/45657")] public void ReadonlyFieldsMembers_Static() { string source = @" public struct Container { public int content; } public static class C { public static readonly Container field; public static int InitOnlyProperty1 { init { field.content = value; } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (13,9): error CS8856: The 'init' accessor is not valid on static members // init Diagnostic(ErrorCode.ERR_BadInitAccessor, "init").WithLocation(13, 9), // (15,13): error CS1650: Fields of static readonly field 'C.field' cannot be assigned to (except in a static constructor or a variable initializer) // field.content = value; Diagnostic(ErrorCode.ERR_AssgReadonlyStatic2, "field.content").WithArguments("C.field").WithLocation(15, 13) ); } [Theory] [InlineData(true)] [InlineData(false)] public void ReadonlyFields_Metadata(bool emitAsImage) { string lib_cs = @" public class C { public readonly string field; } "; var libComp = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class Derived : C { public Derived() { field = null; // 1 _ = new C() { field = null }; // 2 } public void M2() { field = null; // 3 _ = new C() { field = null }; // 4 } public int InitOnlyProperty2 { init { field = null; // 5 } } } "; var comp = CreateCompilation(source, references: new[] { emitAsImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the class in which the field is defined or a variable initializer)) // field = null; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(6, 9), // (7,23): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // _ = new C() { field = null }; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(7, 23), // (12,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(12, 9), // (13,23): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // _ = new C() { field = null }; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(13, 23), // (20,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 5 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(20, 13) ); } [Fact] public void TestGetSpeculativeSemanticModelForPropertyAccessorBody() { var compilation = CreateCompilation(@" class R { private int _p; } class C : R { private int M { init { int y = 1000; } } } "); var blockStatement = (BlockSyntax)SyntaxFactory.ParseStatement(@" { int z = 0; _p = 123L; } "); var tree = compilation.SyntaxTrees[0]; var root = tree.GetCompilationUnitRoot(); var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true); AccessorDeclarationSyntax accessorDecl = root.DescendantNodes().OfType<AccessorDeclarationSyntax>().Single(); var speculatedMethod = accessorDecl.ReplaceNode(accessorDecl.Body, blockStatement); SemanticModel speculativeModel; var success = model.TryGetSpeculativeSemanticModelForMethodBody( accessorDecl.Body.Statements[0].SpanStart, speculatedMethod, out speculativeModel); Assert.True(success); Assert.NotNull(speculativeModel); var p = speculativeModel.SyntaxTree.GetRoot() .DescendantNodes() .OfType<IdentifierNameSyntax>() .Single(s => s.Identifier.ValueText == "_p"); var symbolSpeculation = speculativeModel.GetSpeculativeSymbolInfo(p.FullSpan.Start, p, SpeculativeBindingOption.BindAsExpression); Assert.Equal("_p", symbolSpeculation.Symbol.Name); var typeSpeculation = speculativeModel.GetSpeculativeTypeInfo(p.FullSpan.Start, p, SpeculativeBindingOption.BindAsExpression); Assert.Equal("Int32", typeSpeculation.Type.Name); } [Fact] public void BlockBodyAndExpressionBody_14() { var comp = CreateCompilation(new[] { @" public class C { static int P1 { get; set; } int P2 { init { P1 = 1; } => P1 = 1; } } ", IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (7,9): error CS8057: Block bodies and expression bodies cannot both be provided. // init { P1 = 1; } => P1 = 1; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "init { P1 = 1; } => P1 = 1;").WithLocation(7, 9) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>(); Assert.Equal(2, nodes.Count()); foreach (var assign in nodes) { var node = assign.Left; Assert.Equal("P1", node.ToString()); Assert.Equal("System.Int32 C.P1 { get; set; }", model.GetSymbolInfo(node).Symbol.ToTestDisplayString()); } } [Fact] public void ModReqOnSetAccessorParameter() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance void set_Property ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Property() { .set instance void C::set_Property(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override int Property { set { throw null; } } } public class Derived2 : C { public override int Property { init { throw null; } } } public class D { void M(C c) { c.Property = 42; c.set_Property(42); } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,36): error CS0570: 'C.Property.set' is not supported by the language // public override int Property { set { throw null; } } Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("C.Property.set").WithLocation(4, 36), // (8,25): error CS8853: 'Derived2.Property' must match by init-only of overridden member 'C.Property' // public override int Property { init { throw null; } } Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("Derived2.Property", "C.Property").WithLocation(8, 25), // (8,36): error CS0570: 'C.Property.set' is not supported by the language // public override int Property { init { throw null; } } Diagnostic(ErrorCode.ERR_BindToBogus, "init").WithArguments("C.Property.set").WithLocation(8, 36), // (14,11): error CS0570: 'C.Property.set' is not supported by the language // c.Property = 42; Diagnostic(ErrorCode.ERR_BindToBogus, "Property").WithArguments("C.Property.set").WithLocation(14, 11), // (15,11): error CS0571: 'C.Property.set': cannot explicitly call operator or accessor // c.set_Property(42); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_Property").WithArguments("C.Property.set").WithLocation(15, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.Null(property0.GetMethod); Assert.False(property0.MustCallMethodsDirectly); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); var property1 = (PropertySymbol)comp.GlobalNamespace.GetMember("Derived.Property"); Assert.Null(property1.GetMethod); Assert.False(property1.SetMethod.HasUseSiteError); Assert.False(property1.SetMethod.Parameters[0].Type.IsErrorType()); var property2 = (PropertySymbol)comp.GlobalNamespace.GetMember("Derived2.Property"); Assert.Null(property2.GetMethod); Assert.False(property2.SetMethod.HasUseSiteError); Assert.False(property2.SetMethod.Parameters[0].Type.IsErrorType()); } [Fact] public void ModReqOnSetAccessorParameter_AndProperty() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance void set_Property ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) Property() { .set instance void C::set_Property(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override int Property { set { throw null; } } } public class Derived2 : C { public override int Property { init { throw null; } } } public class D { void M(C c) { c.Property = 42; c.set_Property(42); } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,25): error CS0569: 'Derived.Property': cannot override 'C.Property' because it is not supported by the language // public override int Property { set { throw null; } } Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "Property").WithArguments("Derived.Property", "C.Property").WithLocation(4, 25), // (8,25): error CS0569: 'Derived2.Property': cannot override 'C.Property' because it is not supported by the language // public override int Property { init { throw null; } } Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "Property").WithArguments("Derived2.Property", "C.Property").WithLocation(8, 25), // (14,11): error CS1546: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor method 'C.set_Property(int)' // c.Property = 42; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "Property").WithArguments("C.Property", "C.set_Property(int)").WithLocation(14, 11), // (15,11): error CS0570: 'C.set_Property(int)' is not supported by the language // c.set_Property(42); Diagnostic(ErrorCode.ERR_BindToBogus, "set_Property").WithArguments("C.set_Property(int)").WithLocation(15, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.True(property0.HasUseSiteError); Assert.True(property0.HasUnsupportedMetadata); Assert.True(property0.MustCallMethodsDirectly); Assert.Equal("System.Int32", property0.Type.ToTestDisplayString()); Assert.Null(property0.GetMethod); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); var property1 = (PropertySymbol)comp.GlobalNamespace.GetMember("Derived.Property"); Assert.False(property1.HasUseSiteError); Assert.Null(property1.GetMethod); Assert.False(property1.SetMethod.HasUseSiteError); Assert.False(property1.SetMethod.Parameters[0].Type.IsErrorType()); var property2 = (PropertySymbol)comp.GlobalNamespace.GetMember("Derived2.Property"); Assert.False(property2.HasUseSiteError); Assert.Null(property2.GetMethod); Assert.False(property2.SetMethod.HasUseSiteError); Assert.False(property2.SetMethod.Parameters[0].Type.IsErrorType()); } [Fact] public void ModReqOnSetAccessorParameter_IndexerParameter() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .custom instance void System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6d 00 00 ) .method public hidebysig specialname newslot virtual instance void set_Item ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) i, int32 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Item(int32 modreq(System.Runtime.CompilerServices.IsExternalInit) i) { .set instance void C::set_Item(int32 modreq(System.Runtime.CompilerServices.IsExternalInit), int32) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Reflection.DefaultMemberAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor ( string memberName ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override int this[int i] { set { throw null; } } } public class Derived2 : C { public override int this[int i] { init { throw null; } } } public class D { void M(C c) { c[42] = 43; c.set_Item(42, 43); } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,25): error CS0569: 'Derived.this[int]': cannot override 'C.this[int]' because it is not supported by the language // public override int this[int i] { set { throw null; } } Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "this").WithArguments("Derived.this[int]", "C.this[int]").WithLocation(4, 25), // (8,25): error CS0569: 'Derived2.this[int]': cannot override 'C.this[int]' because it is not supported by the language // public override int this[int i] { init { throw null; } } Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "this").WithArguments("Derived2.this[int]", "C.this[int]").WithLocation(8, 25), // (14,9): error CS1546: Property, indexer, or event 'C.this[int]' is not supported by the language; try directly calling accessor method 'C.set_Item(int, int)' // c[42] = 43; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "c[42]").WithArguments("C.this[int]", "C.set_Item(int, int)").WithLocation(14, 9), // (15,11): error CS0570: 'C.set_Item(int, int)' is not supported by the language // c.set_Item(42, 43); Diagnostic(ErrorCode.ERR_BindToBogus, "set_Item").WithArguments("C.set_Item(int, int)").WithLocation(15, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.this[]"); Assert.True(property0.HasUseSiteError); Assert.True(property0.MustCallMethodsDirectly); Assert.Null(property0.GetMethod); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); } [Fact] public void ModReqOnIndexerValue() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .custom instance void System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6d 00 00 ) .method public hidebysig specialname newslot virtual instance void set_Item ( int32 i, int32 modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Item(int32 i) { .set instance void C::set_Item(int32, int32 modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Reflection.DefaultMemberAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor ( string memberName ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override int this[int i] { set { throw null; } } } public class Derived2 : C { public override int this[int i] { init { throw null; } } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,39): error CS0570: 'C.this[int].set' is not supported by the language // public override int this[int i] { set { throw null; } } Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("C.this[int].set").WithLocation(4, 39), // (8,25): error CS8853: 'Derived2.this[int]' must match by init-only of overridden member 'C.this[int]' // public override int this[int i] { init { throw null; } } Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "this").WithArguments("Derived2.this[int]", "C.this[int]").WithLocation(8, 25), // (8,39): error CS0570: 'C.this[int].set' is not supported by the language // public override int this[int i] { init { throw null; } } Diagnostic(ErrorCode.ERR_BindToBogus, "init").WithArguments("C.this[int].set").WithLocation(8, 39) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.this[]"); Assert.False(property0.HasUseSiteError); Assert.False(property0.MustCallMethodsDirectly); Assert.Null(property0.GetMethod); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[1].HasUnsupportedMetadata); } [Fact] public void ModReqOnStaticMethod() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig static void modreq(System.Runtime.CompilerServices.IsExternalInit) M () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void M2() { C.M(); } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,11): error CS0570: 'C.M()' is not supported by the language // C.M(); Diagnostic(ErrorCode.ERR_BindToBogus, "M").WithArguments("C.M()").WithLocation(6, 11) ); var method = (PEMethodSymbol)comp.GlobalNamespace.GetMember("C.M"); Assert.False(method.IsInitOnly); Assert.False(method.GetPublicSymbol().IsInitOnly); Assert.True(method.HasUseSiteError); Assert.True(method.HasUnsupportedMetadata); } [Fact] public void ModReqOnStaticSet() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig newslot specialname static void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 P() { .set void modreq(System.Runtime.CompilerServices.IsExternalInit) C::set_P(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void M2() { C.P = 2; } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,11): error CS0570: 'C.P.set' is not supported by the language // C.P = 2; Diagnostic(ErrorCode.ERR_BindToBogus, "P").WithArguments("C.P.set").WithLocation(6, 11) ); var method = (PEMethodSymbol)comp.GlobalNamespace.GetMember("C.set_P"); Assert.False(method.IsInitOnly); Assert.False(method.GetPublicSymbol().IsInitOnly); Assert.True(method.HasUseSiteError); Assert.True(method.HasUnsupportedMetadata); } [Fact] public void ModReqOnMethodParameter() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig newslot virtual instance void M ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) i ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override void M() { } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,26): error CS0115: 'Derived.M()': no suitable method found to override // public override void M() { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M").WithArguments("Derived.M()").WithLocation(4, 26) ); var method0 = (PEMethodSymbol)comp.GlobalNamespace.GetMember("C.M"); Assert.True(method0.HasUseSiteError); Assert.True(method0.HasUnsupportedMetadata); Assert.True(method0.Parameters[0].HasUnsupportedMetadata); } [Fact] public void ModReqOnInitOnlySetterOfRefProperty() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32& get_Property () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property ( int32& modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32& Property() { .get instance int32& C::get_Property() .set instance void C::set_Property(int32& modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void M(C c, ref int i) { _ = c.get_Property(); c.set_Property(i); // 1 _ = c.Property; // 2 c.Property = i; // 3 } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (7,11): error CS0570: 'C.set_Property(ref int)' is not supported by the language // c.set_Property(i); // 1 Diagnostic(ErrorCode.ERR_BindToBogus, "set_Property").WithArguments("C.set_Property(ref int)").WithLocation(7, 11), // (9,15): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // _ = c.Property; // 2 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(9, 15), // (10,11): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // c.Property = i; // 3 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(10, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property0.HasUseSiteError); Assert.True(property0.MustCallMethodsDirectly); Assert.False(property0.GetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); Assert.False(property0.SetMethod.IsInitOnly); Assert.False(property0.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void ModReqOnRefProperty_OnRefReturn() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) get_Property () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property ( int32& modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) Property() { .get instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) C::get_Property() .set instance void C::set_Property(int32& modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void M(C c, ref int i) { _ = c.get_Property(); // 1 c.set_Property(i); // 2 _ = c.Property; // 3 c.Property = i; // 4 } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,15): error CS0570: 'C.get_Property()' is not supported by the language // _ = c.get_Property(); // 1 Diagnostic(ErrorCode.ERR_BindToBogus, "get_Property").WithArguments("C.get_Property()").WithLocation(6, 15), // (7,11): error CS0570: 'C.set_Property(ref int)' is not supported by the language // c.set_Property(i); // 2 Diagnostic(ErrorCode.ERR_BindToBogus, "set_Property").WithArguments("C.set_Property(ref int)").WithLocation(7, 11), // (9,15): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // _ = c.Property; // 3 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(9, 15), // (10,11): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // c.Property = i; // 4 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(10, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.True(property0.HasUseSiteError); Assert.True(property0.MustCallMethodsDirectly); Assert.Equal("System.Runtime.CompilerServices.IsExternalInit", property0.RefCustomModifiers.Single().Modifier.ToTestDisplayString()); Assert.Empty(property0.TypeWithAnnotations.CustomModifiers); Assert.True(property0.GetMethod.HasUseSiteError); Assert.True(property0.GetMethod.HasUnsupportedMetadata); Assert.True(property0.GetMethod.ReturnsByRef); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); Assert.False(property0.SetMethod.IsInitOnly); Assert.False(property0.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void ModReqOnRefProperty_OnReturn() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& get_Property () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& Property() { .get instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& C::get_Property() .set instance void C::set_Property(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)&) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void M(C c, ref int i) { _ = c.get_Property(); // 1 c.set_Property(i); // 2 _ = c.Property; // 3 c.Property = i; // 4 } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,15): error CS0570: 'C.get_Property()' is not supported by the language // _ = c.get_Property(); // 1 Diagnostic(ErrorCode.ERR_BindToBogus, "get_Property").WithArguments("C.get_Property()").WithLocation(6, 15), // (7,11): error CS0570: 'C.set_Property(ref int)' is not supported by the language // c.set_Property(i); // 2 Diagnostic(ErrorCode.ERR_BindToBogus, "set_Property").WithArguments("C.set_Property(ref int)").WithLocation(7, 11), // (9,15): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // _ = c.Property; // 3 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(9, 15), // (10,11): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // c.Property = i; // 4 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(10, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.True(property0.HasUseSiteError); Assert.True(property0.MustCallMethodsDirectly); Assert.Empty(property0.RefCustomModifiers); Assert.Equal("System.Runtime.CompilerServices.IsExternalInit", property0.TypeWithAnnotations.CustomModifiers.Single().Modifier.ToTestDisplayString()); Assert.Equal("System.Int32", property0.TypeWithAnnotations.Type.ToTestDisplayString()); Assert.True(property0.GetMethod.HasUseSiteError); Assert.True(property0.GetMethod.HasUnsupportedMetadata); Assert.True(property0.GetMethod.ReturnsByRef); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); Assert.False(property0.SetMethod.IsInitOnly); Assert.False(property0.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void ModReqOnGetAccessorReturnValue() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) get_Property () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property ( int32 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Property() { .get instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) C::get_Property() .set instance void C::set_Property(int32) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override int Property { get { throw null; } } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,36): error CS0570: 'C.Property.get' is not supported by the language // public override int Property { get { throw null; } } Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("C.Property.get").WithLocation(4, 36) ); var property = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().GetMethod.IsInitOnly); Assert.True(property.GetMethod.HasUseSiteError); Assert.True(property.GetMethod.HasUnsupportedMetadata); Assert.False(property.SetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().SetMethod.IsInitOnly); Assert.False(property.SetMethod.HasUseSiteError); } [Fact] public void TestSyntaxFacts() { Assert.True(SyntaxFacts.IsAccessorDeclaration(SyntaxKind.InitAccessorDeclaration)); Assert.True(SyntaxFacts.IsAccessorDeclarationKeyword(SyntaxKind.InitKeyword)); } [Fact] public void NoCascadingErrorsInStaticConstructor() { string source = @" public class C { public string Property { get { throw null; } init { throw null; } } static C() { Property = null; // 1 this.Property = null; // 2 } } public class D : C { static D() { Property = null; // 3 this.Property = null; // 4 base.Property = null; // 5 } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (7,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // Property = null; // 1 Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(7, 9), // (8,9): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // this.Property = null; // 2 Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this").WithLocation(8, 9), // (15,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // Property = null; // 3 Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(15, 9), // (16,9): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // this.Property = null; // 4 Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this").WithLocation(16, 9), // (17,9): error CS1511: Keyword 'base' is not available in a static method // base.Property = null; // 5 Diagnostic(ErrorCode.ERR_BaseInStaticMeth, "base").WithLocation(17, 9) ); } [Fact] public void LocalFunctionsAreNotInitOnly() { var comp = CreateCompilation(new[] { @" public class C { delegate void Delegate(); void M() { local(); void local() { } } } ", IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var localFunctionSyntax = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var localFunctionSymbol = model.GetDeclaredSymbol(localFunctionSyntax).GetSymbol<LocalFunctionSymbol>(); Assert.False(localFunctionSymbol.IsInitOnly); Assert.False(localFunctionSymbol.GetPublicSymbol().IsInitOnly); var delegateSyntax = tree.GetRoot().DescendantNodes().OfType<DelegateDeclarationSyntax>().Single(); var delegateMemberSymbols = model.GetDeclaredSymbol(delegateSyntax).GetSymbol<SourceNamedTypeSymbol>().GetMembers(); Assert.True(delegateMemberSymbols.All(m => m is SourceDelegateMethodSymbol)); foreach (var member in delegateMemberSymbols) { if (member is MethodSymbol method) { Assert.False(method.IsInitOnly); Assert.False(method.GetPublicSymbol().IsInitOnly); } } } [Fact] public void RetargetProperties_WithInitOnlySetter() { var source0 = @" public struct S { public int Property { get; init; } } "; var source1 = @" class Program { public static void Main() { var s = new S() { Property = 42 }; System.Console.WriteLine(s.Property); } } "; var source2 = @" class Program { public static void Main() { var s = new S() { Property = 43 }; System.Console.WriteLine(s.Property); } } "; var comp1 = CreateCompilation(new[] { source0, source1, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); // PEVerify: [ : S::set_Property] Cannot change initonly field outside its .ctor. CompileAndVerify(comp1, expectedOutput: "42", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails); var comp1Ref = new[] { comp1.ToMetadataReference() }; var comp7 = CreateCompilation(source2, references: comp1Ref, targetFramework: TargetFramework.Mscorlib46, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); CompileAndVerify(comp7, expectedOutput: "43"); var property = comp7.GetMember<PropertySymbol>("S.Property"); var setter = (RetargetingMethodSymbol)property.SetMethod; Assert.True(setter.IsInitOnly); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyStruct_AutoProp() { var verifier = CompileAndVerify(new[] { IsExternalInitTypeDefinition, @" var s = new S { I = 1 }; System.Console.Write(s.I); public readonly struct S { public int I { get; init; } } " }, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails, expectedOutput: "1"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (S V_0, //s S V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: call ""void S.I.init"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: call ""int S.I.get"" IL_0019: call ""void System.Console.Write(int)"" IL_001e: ret } "); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyStruct_ManualProp() { var verifier = CompileAndVerify(new[] { IsExternalInitTypeDefinition, @" var s = new S { I = 1 }; System.Console.Write(s.I); public readonly struct S { private readonly int i; public int I { get => i; init => i = value; } } " }, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails, expectedOutput: "1"); var s = verifier.Compilation.GetTypeByMetadataName("S"); var i = s.GetMember<IPropertySymbol>("I"); Assert.False(i.SetMethod.IsReadOnly); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (S V_0, //s S V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: call ""void S.I.init"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: call ""int S.I.get"" IL_0019: call ""void System.Console.Write(int)"" IL_001e: ret } "); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyProperty_AutoProp() { var verifier = CompileAndVerify(new[] { IsExternalInitTypeDefinition, @" var s = new S { I = 1 }; System.Console.Write(s.I); public struct S { public readonly int I { get; init; } } " }, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails, expectedOutput: "1"); var s = verifier.Compilation.GetTypeByMetadataName("S"); var i = s.GetMember<IPropertySymbol>("I"); Assert.False(i.SetMethod.IsReadOnly); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (S V_0, //s S V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: call ""void S.I.init"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: call ""readonly int S.I.get"" IL_0019: call ""void System.Console.Write(int)"" IL_001e: ret } "); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyProperty_ManualProp() { var verifier = CompileAndVerify(new[] { IsExternalInitTypeDefinition, @" var s = new S { I = 1 }; System.Console.Write(s.I); public struct S { private readonly int i; public readonly int I { get => i; init => i = value; } } " }, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails, expectedOutput: "1"); var s = verifier.Compilation.GetTypeByMetadataName("S"); var i = s.GetMember<IPropertySymbol>("I"); Assert.False(i.SetMethod.IsReadOnly); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (S V_0, //s S V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: call ""void S.I.init"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: call ""readonly int S.I.get"" IL_0019: call ""void System.Console.Write(int)"" IL_001e: ret } "); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyInit_AutoProp() { var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, @" public struct S { public int I { get; readonly init; } } " }); comp.VerifyDiagnostics( // (4,34): error CS8903: 'init' accessors cannot be marked 'readonly'. Mark 'S.I' readonly instead. // public int I { get; readonly init; } Diagnostic(ErrorCode.ERR_InitCannotBeReadonly, "init", isSuppressed: false).WithArguments("S.I").WithLocation(4, 34) ); var s = ((Compilation)comp).GetTypeByMetadataName("S"); var i = s.GetMember<IPropertySymbol>("I"); Assert.False(i.SetMethod.IsReadOnly); Assert.True(((Symbols.PublicModel.PropertySymbol)i).GetSymbol<PropertySymbol>().SetMethod.IsDeclaredReadOnly); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyInit_ManualProp() { var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, @" public struct S { public int I { get => 1; readonly init { } } } " }); comp.VerifyDiagnostics( // (4,39): error CS8903: 'init' accessors cannot be marked 'readonly'. Mark 'S.I' readonly instead. // public int I { get => 1; readonly init { } } Diagnostic(ErrorCode.ERR_InitCannotBeReadonly, "init", isSuppressed: false).WithArguments("S.I").WithLocation(4, 39) ); var s = ((Compilation)comp).GetTypeByMetadataName("S"); var i = s.GetMember<IPropertySymbol>("I"); Assert.False(i.SetMethod.IsReadOnly); Assert.True(((Symbols.PublicModel.PropertySymbol)i).GetSymbol<PropertySymbol>().SetMethod.IsDeclaredReadOnly); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyInit_ReassignsSelf() { var verifier = CompileAndVerify(new[] { IsExternalInitTypeDefinition, @" var s = new S { I1 = 1, I2 = 2 }; System.Console.WriteLine($""I1 is {s.I1}""); public readonly struct S { private readonly int i; public readonly int I1 { get => i; init => i = value; } public int I2 { get => throw null; init { System.Console.WriteLine($""I1 was {I1}""); this = default; } } } " }, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails, expectedOutput: @"I1 was 1 I1 is 0"); var s = verifier.Compilation.GetTypeByMetadataName("S"); var i1 = s.GetMember<IPropertySymbol>("I1"); Assert.False(i1.SetMethod.IsReadOnly); var i2 = s.GetMember<IPropertySymbol>("I2"); Assert.False(i2.SetMethod.IsReadOnly); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 54 (0x36) .maxstack 2 .locals init (S V_0, //s S V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: call ""void S.I1.init"" IL_0010: ldloca.s V_1 IL_0012: ldc.i4.2 IL_0013: call ""void S.I2.init"" IL_0018: ldloc.1 IL_0019: stloc.0 IL_001a: ldstr ""I1 is {0}"" IL_001f: ldloca.s V_0 IL_0021: call ""int S.I1.get"" IL_0026: box ""int"" IL_002b: call ""string string.Format(string, object)"" IL_0030: call ""void System.Console.WriteLine(string)"" IL_0035: ret } "); } [Fact] [WorkItem(50126, "https://github.com/dotnet/roslyn/issues/50126")] public void NestedInitializer() { var source = @" using System; Person person = new Person(""j"", ""p""); Container c = new Container(person) { Person = { FirstName = ""c"" } }; public record Person(String FirstName, String LastName); public record Container(Person Person); "; var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, source }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (7,16): error CS8852: Init-only property or indexer 'Person.FirstName' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Person = { FirstName = "c" } Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "FirstName").WithArguments("Person.FirstName").WithLocation(7, 16) ); } [Fact] [WorkItem(50126, "https://github.com/dotnet/roslyn/issues/50126")] public void NestedInitializer_NewT() { var source = @" using System; class C { void M<T>(Person person) where T : Container, new() { Container c = new T() { Person = { FirstName = ""c"" } }; } } public record Person(String FirstName, String LastName); public record Container(Person Person); "; var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, source }); comp.VerifyEmitDiagnostics( // (10,24): error CS8852: Init-only property or indexer 'Person.FirstName' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Person = { FirstName = "c" } Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "FirstName").WithArguments("Person.FirstName").WithLocation(10, 24) ); } [Fact] [WorkItem(50126, "https://github.com/dotnet/roslyn/issues/50126")] public void NestedInitializer_UsingGenericType() { var source = @" using System; Person person = new Person(""j"", ""p""); var c = new Container<Person>(person) { PropertyT = { FirstName = ""c"" } }; public record Person(String FirstName, String LastName); public record Container<T>(T PropertyT) where T : Person; "; var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, source }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (7,19): error CS8852: Init-only property or indexer 'Person.FirstName' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // PropertyT = { FirstName = "c" } Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "FirstName").WithArguments("Person.FirstName").WithLocation(7, 19) ); } [Fact] [WorkItem(50126, "https://github.com/dotnet/roslyn/issues/50126")] public void NestedInitializer_UsingNew() { var source = @" using System; Person person = new Person(""j"", ""p""); Container c = new Container(person) { Person = new Person(""j"", ""p"") { FirstName = ""c"" } }; Console.Write(c.Person.FirstName); public record Person(String FirstName, String LastName); public record Container(Person Person); "; var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, source }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); // PEVerify: Cannot change initonly field outside its .ctor. CompileAndVerify(comp, expectedOutput: "c", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails); } [Fact] [WorkItem(50126, "https://github.com/dotnet/roslyn/issues/50126")] public void NestedInitializer_UsingNewNoPia() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58277"")] [CoClass(typeof(ClassITest28))] public interface ITest28 { int Property { get; init; } } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest28 //: ITest28 { public ClassITest28(int x) { } } "; var piaCompilation = CreateCompilationWithMscorlib45(new[] { IsExternalInitTypeDefinition, pia }, options: TestOptions.DebugDll); CompileAndVerify(piaCompilation); string source = @" class UsePia { public ITest28 Property2 { get; init; } public static void Main() { var x1 = new ITest28() { Property = 42 }; var x2 = new UsePia() { Property2 = { Property = 43 } }; } }"; var compilation = CreateCompilationWithMscorlib45(new[] { source }, new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) }, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (9,47): error CS8852: Init-only property or indexer 'ITest28.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // var x2 = new UsePia() { Property2 = { Property = 43 } }; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("ITest28.Property").WithLocation(9, 47) ); } [Fact, WorkItem(50696, "https://github.com/dotnet/roslyn/issues/50696")] public void PickAmbiguousTypeFromCorlib() { var corlib_cs = @" namespace System { public class Object { } public struct Int32 { } public struct Boolean { } public class String { } public class ValueType { } public struct Void { } public class Attribute { } } "; string source = @" public class C { public int Property { get; init; } } "; var corlibWithoutIsExternalInitRef = CreateEmptyCompilation(corlib_cs, assemblyName: "corlibWithoutIsExternalInit") .EmitToImageReference(); var corlibWithIsExternalInitRef = CreateEmptyCompilation(corlib_cs + IsExternalInitTypeDefinition, assemblyName: "corlibWithIsExternalInit") .EmitToImageReference(); var libWithIsExternalInitRef = CreateEmptyCompilation(IsExternalInitTypeDefinition, references: new[] { corlibWithoutIsExternalInitRef }, assemblyName: "libWithIsExternalInit") .EmitToImageReference(); var libWithIsExternalInitRef2 = CreateEmptyCompilation(IsExternalInitTypeDefinition, references: new[] { corlibWithoutIsExternalInitRef }, assemblyName: "libWithIsExternalInit2") .EmitToImageReference(); { // type in source var comp = CreateEmptyCompilation(new[] { source, IsExternalInitTypeDefinition }, references: new[] { corlibWithoutIsExternalInitRef }, assemblyName: "source"); comp.VerifyEmitDiagnostics(); verify(comp, "source"); } { // type in library var comp = CreateEmptyCompilation(new[] { source }, references: new[] { corlibWithoutIsExternalInitRef, libWithIsExternalInitRef }, assemblyName: "source"); comp.VerifyEmitDiagnostics(); verify(comp, "libWithIsExternalInit"); } { // type in corlib and in source var comp = CreateEmptyCompilation(new[] { source, IsExternalInitTypeDefinition }, references: new[] { corlibWithIsExternalInitRef }, assemblyName: "source"); comp.VerifyEmitDiagnostics(); verify(comp, "source"); } { // type in corlib, in library and in source var comp = CreateEmptyCompilation(new[] { source, IsExternalInitTypeDefinition }, references: new[] { corlibWithIsExternalInitRef, libWithIsExternalInitRef }, assemblyName: "source"); comp.VerifyEmitDiagnostics(); verify(comp, "source"); } { // type in corlib and in two libraries var comp = CreateEmptyCompilation(source, references: new[] { corlibWithIsExternalInitRef, libWithIsExternalInitRef, libWithIsExternalInitRef2 }); comp.VerifyEmitDiagnostics(); verify(comp, "corlibWithIsExternalInit"); } { // type in corlib and in two libraries (corlib in middle) var comp = CreateEmptyCompilation(source, references: new[] { libWithIsExternalInitRef, corlibWithIsExternalInitRef, libWithIsExternalInitRef2 }); comp.VerifyEmitDiagnostics(); verify(comp, "corlibWithIsExternalInit"); } { // type in corlib and in two libraries (corlib last) var comp = CreateEmptyCompilation(source, references: new[] { libWithIsExternalInitRef, libWithIsExternalInitRef2, corlibWithIsExternalInitRef }); comp.VerifyEmitDiagnostics(); verify(comp, "corlibWithIsExternalInit"); } { // type in corlib and in two libraries, but flag is set var comp = CreateEmptyCompilation(source, references: new[] { corlibWithIsExternalInitRef, libWithIsExternalInitRef, libWithIsExternalInitRef2 }, options: TestOptions.DebugDll.WithTopLevelBinderFlags(BinderFlags.IgnoreCorLibraryDuplicatedTypes)); comp.VerifyEmitDiagnostics( // (4,32): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported // public int Property { get; init; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit").WithLocation(4, 32) ); } { // type in two libraries var comp = CreateEmptyCompilation(source, references: new[] { corlibWithoutIsExternalInitRef, libWithIsExternalInitRef, libWithIsExternalInitRef2 }); comp.VerifyEmitDiagnostics( // (4,32): error CS018: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported // public int Property { get; init; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit").WithLocation(4, 32) ); } { // type in two libraries, but flag is set var comp = CreateEmptyCompilation(source, references: new[] { corlibWithoutIsExternalInitRef, libWithIsExternalInitRef, libWithIsExternalInitRef2 }, options: TestOptions.DebugDll.WithTopLevelBinderFlags(BinderFlags.IgnoreCorLibraryDuplicatedTypes)); comp.VerifyEmitDiagnostics( // (4,32): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported // public int Property { get; init; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit").WithLocation(4, 32) ); } { // type in corlib and in a library var comp = CreateEmptyCompilation(source, references: new[] { corlibWithIsExternalInitRef, libWithIsExternalInitRef }); comp.VerifyEmitDiagnostics(); verify(comp, "corlibWithIsExternalInit"); } { // type in corlib and in a library (reverse order) var comp = CreateEmptyCompilation(source, references: new[] { libWithIsExternalInitRef, corlibWithIsExternalInitRef }); comp.VerifyEmitDiagnostics(); verify(comp, "corlibWithIsExternalInit"); } { // type in corlib and in a library, but flag is set var comp = CreateEmptyCompilation(source, references: new[] { corlibWithIsExternalInitRef, libWithIsExternalInitRef }, options: TestOptions.DebugDll.WithTopLevelBinderFlags(BinderFlags.IgnoreCorLibraryDuplicatedTypes)); comp.VerifyEmitDiagnostics(); Assert.Equal("libWithIsExternalInit", comp.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IsExternalInit).ContainingAssembly.Name); Assert.Equal("corlibWithIsExternalInit", comp.GetTypeByMetadataName("System.Runtime.CompilerServices.IsExternalInit").ContainingAssembly.Name); } static void verify(CSharpCompilation comp, string expectedAssemblyName) { var modifier = ((SourcePropertySymbol)comp.GlobalNamespace.GetMember("C.Property")).SetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single(); Assert.Equal(expectedAssemblyName, modifier.Modifier.ContainingAssembly.Name); Assert.Equal(expectedAssemblyName, comp.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IsExternalInit).ContainingAssembly.Name); Assert.Equal(expectedAssemblyName, comp.GetTypeByMetadataName("System.Runtime.CompilerServices.IsExternalInit").ContainingAssembly.Name); } } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Workspaces/Remote/ServiceHub/Services/ProjectTelemetry/ApiUsageIncrementalAnalyzerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Telemetry; using Microsoft.VisualStudio.Telemetry; namespace Microsoft.CodeAnalysis.Remote.Telemetry { /// <summary> /// Creates an <see cref="IIncrementalAnalyzer"/> that collects Api usage information from metadata references /// in current solution. /// </summary> [ExportIncrementalAnalyzerProvider(nameof(ApiUsageIncrementalAnalyzerProvider), new[] { WorkspaceKind.RemoteWorkspace }), Shared] internal sealed class ApiUsageIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ApiUsageIncrementalAnalyzerProvider() { } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) { #if DEBUG return new Analyzer(workspace.Services); #else return null; #endif } private sealed class Analyzer : IIncrementalAnalyzer { private readonly HostWorkspaceServices _services; // maximum number of symbols to report per project. private const int Max = 2000; private readonly HashSet<ProjectId> _reported = new HashSet<ProjectId>(); public Analyzer(HostWorkspaceServices services) { _services = services; } public Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellationToken) { lock (_reported) { _reported.Remove(projectId); } return Task.CompletedTask; } public async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken) { var telemetryService = _services.GetRequiredService<IWorkspaceTelemetryService>(); if (!telemetryService.HasActiveSession) { return; } lock (_reported) { // to make sure that we don't report while solution load, we do this heuristic. // if the reason we are called is due to "document being added" to project, we wait for next analyze call. // also, we only report usage information per project once. // this telemetry will only let us know which API ever used, this doesn't care how often/many times an API // used. and this data is approximation not precise information. and we don't care much on how many times // APIs used in the same solution. we are rather more interested in number of solutions or users APIs are used. if (reasons.Contains(PredefinedInvocationReasons.DocumentAdded) || !_reported.Add(project.Id)) { return; } } // if this project has cross language p2p references, then pass in solution, otherwise, don't give in // solution since checking whether symbol is cross language symbol or not is expansive and // we know that population of solution with both C# and VB are very tiny. // so no reason to pay the cost for common cases. var crossLanguageSolutionOpt = project.ProjectReferences.Any(p => project.Solution.GetProject(p.ProjectId)?.Language != project.Language) ? project.Solution : null; var metadataSymbolUsed = new HashSet<ISymbol>(SymbolEqualityComparer.Default); foreach (var document in project.Documents) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var operation in GetOperations(model, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (metadataSymbolUsed.Count > Max) { // collect data up to max per project break; } // this only gather reference and method call symbols but not type being used. // if we want all types from metadata used, we need to add more cases // which will make things more expansive. CollectApisUsed(operation, crossLanguageSolutionOpt, metadataSymbolUsed, cancellationToken); } } var solutionSessionId = project.Solution.State.SolutionAttributes.TelemetryId; var projectGuid = project.State.ProjectInfo.Attributes.TelemetryId; telemetryService.ReportApiUsage(metadataSymbolUsed, solutionSessionId, projectGuid); return; // local functions static void CollectApisUsed( IOperation operation, Solution solutionOpt, HashSet<ISymbol> metadataSymbolUsed, CancellationToken cancellationToken) { switch (operation) { case IMemberReferenceOperation memberOperation: AddIfMetadataSymbol(solutionOpt, memberOperation.Member, metadataSymbolUsed, cancellationToken); break; case IInvocationOperation invocationOperation: AddIfMetadataSymbol(solutionOpt, invocationOperation.TargetMethod, metadataSymbolUsed, cancellationToken); break; case IObjectCreationOperation objectCreation: AddIfMetadataSymbol(solutionOpt, objectCreation.Constructor, metadataSymbolUsed, cancellationToken); break; } } static void AddIfMetadataSymbol( Solution solutionOpt, ISymbol symbol, HashSet<ISymbol> metadataSymbolUsed, CancellationToken cancellationToken) { // get symbol as it is defined in metadata symbol = symbol.OriginalDefinition; if (metadataSymbolUsed.Contains(symbol)) { return; } if (symbol.Locations.All(l => l.Kind == LocationKind.MetadataFile) && solutionOpt?.GetProject(symbol.ContainingAssembly, cancellationToken) == null) { metadataSymbolUsed.Add(symbol); } } static IEnumerable<IOperation> GetOperations(SemanticModel model, CancellationToken cancellationToken) { // root is already there var root = model.SyntaxTree.GetRoot(cancellationToken); // go through all nodes until we find first node that has IOperation foreach (var rootOperation in root.DescendantNodes(n => model.GetOperation(n, cancellationToken) == null) .Select(n => model.GetOperation(n, cancellationToken)) .Where(o => o != null)) { foreach (var operation in rootOperation.DescendantsAndSelf()) { yield return operation; } } } } public Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentResetAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken) => Task.CompletedTask; public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) => false; public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) => Task.CompletedTask; public Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) => Task.CompletedTask; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Telemetry; using Microsoft.VisualStudio.Telemetry; namespace Microsoft.CodeAnalysis.Remote.Telemetry { /// <summary> /// Creates an <see cref="IIncrementalAnalyzer"/> that collects Api usage information from metadata references /// in current solution. /// </summary> [ExportIncrementalAnalyzerProvider(nameof(ApiUsageIncrementalAnalyzerProvider), new[] { WorkspaceKind.RemoteWorkspace }), Shared] internal sealed class ApiUsageIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ApiUsageIncrementalAnalyzerProvider() { } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) { #if DEBUG return new Analyzer(workspace.Services); #else return null; #endif } private sealed class Analyzer : IIncrementalAnalyzer { private readonly HostWorkspaceServices _services; // maximum number of symbols to report per project. private const int Max = 2000; private readonly HashSet<ProjectId> _reported = new HashSet<ProjectId>(); public Analyzer(HostWorkspaceServices services) { _services = services; } public Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellationToken) { lock (_reported) { _reported.Remove(projectId); } return Task.CompletedTask; } public async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken) { var telemetryService = _services.GetRequiredService<IWorkspaceTelemetryService>(); if (!telemetryService.HasActiveSession) { return; } lock (_reported) { // to make sure that we don't report while solution load, we do this heuristic. // if the reason we are called is due to "document being added" to project, we wait for next analyze call. // also, we only report usage information per project once. // this telemetry will only let us know which API ever used, this doesn't care how often/many times an API // used. and this data is approximation not precise information. and we don't care much on how many times // APIs used in the same solution. we are rather more interested in number of solutions or users APIs are used. if (reasons.Contains(PredefinedInvocationReasons.DocumentAdded) || !_reported.Add(project.Id)) { return; } } // if this project has cross language p2p references, then pass in solution, otherwise, don't give in // solution since checking whether symbol is cross language symbol or not is expansive and // we know that population of solution with both C# and VB are very tiny. // so no reason to pay the cost for common cases. var crossLanguageSolutionOpt = project.ProjectReferences.Any(p => project.Solution.GetProject(p.ProjectId)?.Language != project.Language) ? project.Solution : null; var metadataSymbolUsed = new HashSet<ISymbol>(SymbolEqualityComparer.Default); foreach (var document in project.Documents) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var operation in GetOperations(model, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (metadataSymbolUsed.Count > Max) { // collect data up to max per project break; } // this only gather reference and method call symbols but not type being used. // if we want all types from metadata used, we need to add more cases // which will make things more expansive. CollectApisUsed(operation, crossLanguageSolutionOpt, metadataSymbolUsed, cancellationToken); } } var solutionSessionId = project.Solution.State.SolutionAttributes.TelemetryId; var projectGuid = project.State.ProjectInfo.Attributes.TelemetryId; telemetryService.ReportApiUsage(metadataSymbolUsed, solutionSessionId, projectGuid); return; // local functions static void CollectApisUsed( IOperation operation, Solution solutionOpt, HashSet<ISymbol> metadataSymbolUsed, CancellationToken cancellationToken) { switch (operation) { case IMemberReferenceOperation memberOperation: AddIfMetadataSymbol(solutionOpt, memberOperation.Member, metadataSymbolUsed, cancellationToken); break; case IInvocationOperation invocationOperation: AddIfMetadataSymbol(solutionOpt, invocationOperation.TargetMethod, metadataSymbolUsed, cancellationToken); break; case IObjectCreationOperation objectCreation: AddIfMetadataSymbol(solutionOpt, objectCreation.Constructor, metadataSymbolUsed, cancellationToken); break; } } static void AddIfMetadataSymbol( Solution solutionOpt, ISymbol symbol, HashSet<ISymbol> metadataSymbolUsed, CancellationToken cancellationToken) { // get symbol as it is defined in metadata symbol = symbol.OriginalDefinition; if (metadataSymbolUsed.Contains(symbol)) { return; } if (symbol.Locations.All(l => l.Kind == LocationKind.MetadataFile) && solutionOpt?.GetProject(symbol.ContainingAssembly, cancellationToken) == null) { metadataSymbolUsed.Add(symbol); } } static IEnumerable<IOperation> GetOperations(SemanticModel model, CancellationToken cancellationToken) { // root is already there var root = model.SyntaxTree.GetRoot(cancellationToken); // go through all nodes until we find first node that has IOperation foreach (var rootOperation in root.DescendantNodes(n => model.GetOperation(n, cancellationToken) == null) .Select(n => model.GetOperation(n, cancellationToken)) .Where(o => o != null)) { foreach (var operation in rootOperation.DescendantsAndSelf()) { yield return operation; } } } } public Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentResetAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken) => Task.CompletedTask; public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) => false; public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) => Task.CompletedTask; public Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) => Task.CompletedTask; } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Compilers/CSharp/Portable/Binder/ForLoopBinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class ForLoopBinder : LoopBinder { private readonly ForStatementSyntax _syntax; public ForLoopBinder(Binder enclosing, ForStatementSyntax syntax) : base(enclosing) { Debug.Assert(syntax != null); _syntax = syntax; } protected override ImmutableArray<LocalSymbol> BuildLocals() { var locals = ArrayBuilder<LocalSymbol>.GetInstance(); // Declaration and Initializers are mutually exclusive. if (_syntax.Declaration != null) { _syntax.Declaration.Type.VisitRankSpecifiers((rankSpecifier, args) => { foreach (var size in rankSpecifier.Sizes) { if (size.Kind() != SyntaxKind.OmittedArraySizeExpression) { ExpressionVariableFinder.FindExpressionVariables(args.binder, args.locals, size); } } }, (binder: this, locals: locals)); foreach (var vdecl in _syntax.Declaration.Variables) { var localSymbol = MakeLocal(_syntax.Declaration, vdecl, LocalDeclarationKind.RegularVariable); locals.Add(localSymbol); // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionVariableFinder.FindExpressionVariables(this, locals, vdecl); } } else { ExpressionVariableFinder.FindExpressionVariables(this, locals, _syntax.Initializers); } return locals.ToImmutableAndFree(); } internal override BoundForStatement BindForParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { BoundForStatement result = BindForParts(_syntax, originalBinder, diagnostics); return result; } private BoundForStatement BindForParts(ForStatementSyntax node, Binder originalBinder, BindingDiagnosticBag diagnostics) { BoundStatement initializer; // Declaration and Initializers are mutually exclusive. if (_syntax.Declaration != null) { ImmutableArray<BoundLocalDeclaration> unused; initializer = originalBinder.BindForOrUsingOrFixedDeclarations(node.Declaration, LocalDeclarationKind.RegularVariable, diagnostics, out unused); } else { initializer = originalBinder.BindStatementExpressionList(node.Initializers, diagnostics); } BoundExpression condition = null; var innerLocals = ImmutableArray<LocalSymbol>.Empty; ExpressionSyntax conditionSyntax = node.Condition; if (conditionSyntax != null) { originalBinder = originalBinder.GetBinder(conditionSyntax); condition = originalBinder.BindBooleanExpression(conditionSyntax, diagnostics); innerLocals = originalBinder.GetDeclaredLocalsForScope(conditionSyntax); } BoundStatement increment = null; SeparatedSyntaxList<ExpressionSyntax> incrementors = node.Incrementors; if (incrementors.Count > 0) { var scopeDesignator = incrementors.First(); var incrementBinder = originalBinder.GetBinder(scopeDesignator); increment = incrementBinder.BindStatementExpressionList(incrementors, diagnostics); Debug.Assert(increment.Kind != BoundKind.StatementList || ((BoundStatementList)increment).Statements.Length > 1); var locals = incrementBinder.GetDeclaredLocalsForScope(scopeDesignator); if (!locals.IsEmpty) { if (increment.Kind == BoundKind.StatementList) { increment = new BoundBlock(scopeDesignator, locals, ((BoundStatementList)increment).Statements) { WasCompilerGenerated = true }; } else { increment = new BoundBlock(increment.Syntax, locals, ImmutableArray.Create(increment)) { WasCompilerGenerated = true }; } } } var body = originalBinder.BindPossibleEmbeddedStatement(node.Statement, diagnostics); Debug.Assert(this.Locals == this.GetDeclaredLocalsForScope(node)); return new BoundForStatement(node, this.Locals, initializer, innerLocals, condition, increment, body, this.BreakLabel, this.ContinueLabel); } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { if (_syntax == scopeDesignator) { return this.Locals; } throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { throw ExceptionUtilities.Unreachable; } internal override SyntaxNode ScopeDesignator { get { return _syntax; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class ForLoopBinder : LoopBinder { private readonly ForStatementSyntax _syntax; public ForLoopBinder(Binder enclosing, ForStatementSyntax syntax) : base(enclosing) { Debug.Assert(syntax != null); _syntax = syntax; } protected override ImmutableArray<LocalSymbol> BuildLocals() { var locals = ArrayBuilder<LocalSymbol>.GetInstance(); // Declaration and Initializers are mutually exclusive. if (_syntax.Declaration != null) { _syntax.Declaration.Type.VisitRankSpecifiers((rankSpecifier, args) => { foreach (var size in rankSpecifier.Sizes) { if (size.Kind() != SyntaxKind.OmittedArraySizeExpression) { ExpressionVariableFinder.FindExpressionVariables(args.binder, args.locals, size); } } }, (binder: this, locals: locals)); foreach (var vdecl in _syntax.Declaration.Variables) { var localSymbol = MakeLocal(_syntax.Declaration, vdecl, LocalDeclarationKind.RegularVariable); locals.Add(localSymbol); // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionVariableFinder.FindExpressionVariables(this, locals, vdecl); } } else { ExpressionVariableFinder.FindExpressionVariables(this, locals, _syntax.Initializers); } return locals.ToImmutableAndFree(); } internal override BoundForStatement BindForParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { BoundForStatement result = BindForParts(_syntax, originalBinder, diagnostics); return result; } private BoundForStatement BindForParts(ForStatementSyntax node, Binder originalBinder, BindingDiagnosticBag diagnostics) { BoundStatement initializer; // Declaration and Initializers are mutually exclusive. if (_syntax.Declaration != null) { ImmutableArray<BoundLocalDeclaration> unused; initializer = originalBinder.BindForOrUsingOrFixedDeclarations(node.Declaration, LocalDeclarationKind.RegularVariable, diagnostics, out unused); } else { initializer = originalBinder.BindStatementExpressionList(node.Initializers, diagnostics); } BoundExpression condition = null; var innerLocals = ImmutableArray<LocalSymbol>.Empty; ExpressionSyntax conditionSyntax = node.Condition; if (conditionSyntax != null) { originalBinder = originalBinder.GetBinder(conditionSyntax); condition = originalBinder.BindBooleanExpression(conditionSyntax, diagnostics); innerLocals = originalBinder.GetDeclaredLocalsForScope(conditionSyntax); } BoundStatement increment = null; SeparatedSyntaxList<ExpressionSyntax> incrementors = node.Incrementors; if (incrementors.Count > 0) { var scopeDesignator = incrementors.First(); var incrementBinder = originalBinder.GetBinder(scopeDesignator); increment = incrementBinder.BindStatementExpressionList(incrementors, diagnostics); Debug.Assert(increment.Kind != BoundKind.StatementList || ((BoundStatementList)increment).Statements.Length > 1); var locals = incrementBinder.GetDeclaredLocalsForScope(scopeDesignator); if (!locals.IsEmpty) { if (increment.Kind == BoundKind.StatementList) { increment = new BoundBlock(scopeDesignator, locals, ((BoundStatementList)increment).Statements) { WasCompilerGenerated = true }; } else { increment = new BoundBlock(increment.Syntax, locals, ImmutableArray.Create(increment)) { WasCompilerGenerated = true }; } } } var body = originalBinder.BindPossibleEmbeddedStatement(node.Statement, diagnostics); Debug.Assert(this.Locals == this.GetDeclaredLocalsForScope(node)); return new BoundForStatement(node, this.Locals, initializer, innerLocals, condition, increment, body, this.BreakLabel, this.ContinueLabel); } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { if (_syntax == scopeDesignator) { return this.Locals; } throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { throw ExceptionUtilities.Unreachable; } internal override SyntaxNode ScopeDesignator { get { return _syntax; } } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/VisualStudio/Core/Def/Implementation/ColorSchemes/ColorSchemeApplier.ColorSchemeReader.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.Globalization; using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.ColorSchemes { internal partial class ColorSchemeApplier { private static class ColorSchemeReader { private static readonly XmlReaderSettings s_xmlSettings = new() { DtdProcessing = DtdProcessing.Prohibit }; private const string RawColorType = nameof(__VSCOLORTYPE.CT_RAW); private const string SystemColorType = nameof(__VSCOLORTYPE.CT_SYSCOLOR); public static ColorScheme ReadColorScheme(Stream schemeStream) { using var xmlReader = XmlReader.Create(schemeStream, s_xmlSettings); var schemeDocument = XDocument.Load(xmlReader); var themes = schemeDocument .Descendants("Theme") .Select(ReadColorTheme); return new ColorScheme(themes.ToImmutableArray()); } private static ColorTheme ReadColorTheme(XElement themeElement) { var themeName = (string)themeElement.Attribute("Name"); var themeGuid = Guid.Parse((string)themeElement.Attribute("GUID")); var categoryElement = themeElement.Descendants("Category").Single(); var category = ReadColorCategory(categoryElement); return new ColorTheme(themeName, themeGuid, category); } private static ColorCategory ReadColorCategory(XElement categoryElement) { var categoryName = (string)categoryElement.Attribute("Name"); var categoryGuid = Guid.Parse((string)categoryElement.Attribute("GUID")); var colorItems = categoryElement .Descendants("Color") .Select(ReadColorItem) .WhereNotNull(); return new ColorCategory(categoryName, categoryGuid, colorItems.ToImmutableArray()); } private static ColorItem? ReadColorItem(XElement colorElement) { var name = (string)colorElement.Attribute("Name"); var backgroundElement = colorElement.Descendants("Background").SingleOrDefault(); (var backgroundType, var backgroundColor) = backgroundElement is object ? ReadColor(backgroundElement) : (__VSCOLORTYPE.CT_INVALID, (uint?)null); var foregroundElement = colorElement.Descendants("Foreground").SingleOrDefault(); (var foregroundType, var foregroundColor) = foregroundElement is object ? ReadColor(foregroundElement) : (__VSCOLORTYPE.CT_INVALID, (uint?)null); if (backgroundElement is null && foregroundElement is null) { return null; } return new ColorItem(name, backgroundType, backgroundColor, foregroundType, foregroundColor); } private static (__VSCOLORTYPE Type, uint Color) ReadColor(XElement colorElement) { var colorType = (string)colorElement.Attribute("Type"); var sourceColor = (string)colorElement.Attribute("Source"); __VSCOLORTYPE type; uint color; if (colorType == RawColorType) { type = __VSCOLORTYPE.CT_RAW; // The ColorableItemInfo returned by the FontAndColorStorage retuns RGB color information as 0x00BBGGRR. // Optimize for color comparisons by converting ARGB to BGR by ignoring the alpha channel and reversing byte order. var r = sourceColor.Substring(2, 2); var g = sourceColor.Substring(4, 2); var b = sourceColor.Substring(6, 2); color = uint.Parse($"{b}{g}{r}", NumberStyles.HexNumber); } else if (colorType == SystemColorType) { type = __VSCOLORTYPE.CT_SYSCOLOR; color = uint.Parse(sourceColor, NumberStyles.HexNumber); } else { throw ExceptionUtilities.UnexpectedValue(colorType); } return (type, color); } } } }
// Licensed to the .NET Foundation under one or more 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.Globalization; using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.ColorSchemes { internal partial class ColorSchemeApplier { private static class ColorSchemeReader { private static readonly XmlReaderSettings s_xmlSettings = new() { DtdProcessing = DtdProcessing.Prohibit }; private const string RawColorType = nameof(__VSCOLORTYPE.CT_RAW); private const string SystemColorType = nameof(__VSCOLORTYPE.CT_SYSCOLOR); public static ColorScheme ReadColorScheme(Stream schemeStream) { using var xmlReader = XmlReader.Create(schemeStream, s_xmlSettings); var schemeDocument = XDocument.Load(xmlReader); var themes = schemeDocument .Descendants("Theme") .Select(ReadColorTheme); return new ColorScheme(themes.ToImmutableArray()); } private static ColorTheme ReadColorTheme(XElement themeElement) { var themeName = (string)themeElement.Attribute("Name"); var themeGuid = Guid.Parse((string)themeElement.Attribute("GUID")); var categoryElement = themeElement.Descendants("Category").Single(); var category = ReadColorCategory(categoryElement); return new ColorTheme(themeName, themeGuid, category); } private static ColorCategory ReadColorCategory(XElement categoryElement) { var categoryName = (string)categoryElement.Attribute("Name"); var categoryGuid = Guid.Parse((string)categoryElement.Attribute("GUID")); var colorItems = categoryElement .Descendants("Color") .Select(ReadColorItem) .WhereNotNull(); return new ColorCategory(categoryName, categoryGuid, colorItems.ToImmutableArray()); } private static ColorItem? ReadColorItem(XElement colorElement) { var name = (string)colorElement.Attribute("Name"); var backgroundElement = colorElement.Descendants("Background").SingleOrDefault(); (var backgroundType, var backgroundColor) = backgroundElement is object ? ReadColor(backgroundElement) : (__VSCOLORTYPE.CT_INVALID, (uint?)null); var foregroundElement = colorElement.Descendants("Foreground").SingleOrDefault(); (var foregroundType, var foregroundColor) = foregroundElement is object ? ReadColor(foregroundElement) : (__VSCOLORTYPE.CT_INVALID, (uint?)null); if (backgroundElement is null && foregroundElement is null) { return null; } return new ColorItem(name, backgroundType, backgroundColor, foregroundType, foregroundColor); } private static (__VSCOLORTYPE Type, uint Color) ReadColor(XElement colorElement) { var colorType = (string)colorElement.Attribute("Type"); var sourceColor = (string)colorElement.Attribute("Source"); __VSCOLORTYPE type; uint color; if (colorType == RawColorType) { type = __VSCOLORTYPE.CT_RAW; // The ColorableItemInfo returned by the FontAndColorStorage retuns RGB color information as 0x00BBGGRR. // Optimize for color comparisons by converting ARGB to BGR by ignoring the alpha channel and reversing byte order. var r = sourceColor.Substring(2, 2); var g = sourceColor.Substring(4, 2); var b = sourceColor.Substring(6, 2); color = uint.Parse($"{b}{g}{r}", NumberStyles.HexNumber); } else if (colorType == SystemColorType) { type = __VSCOLORTYPE.CT_SYSCOLOR; color = uint.Parse(sourceColor, NumberStyles.HexNumber); } else { throw ExceptionUtilities.UnexpectedValue(colorType); } return (type, color); } } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Features/Core/Portable/Completion/Providers/UnionCompletionItemComparer.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal class UnionCompletionItemComparer : IEqualityComparer<CompletionItem> { public static UnionCompletionItemComparer Instance { get; } = new UnionCompletionItemComparer(); private UnionCompletionItemComparer() { } public bool Equals(CompletionItem x, CompletionItem y) { return x.DisplayText == y.DisplayText && (x.Tags == y.Tags || System.Linq.Enumerable.SequenceEqual(x.Tags, y.Tags)); } public int GetHashCode(CompletionItem obj) => Hash.Combine(obj.DisplayText.GetHashCode(), obj.Tags.Length); } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal class UnionCompletionItemComparer : IEqualityComparer<CompletionItem> { public static UnionCompletionItemComparer Instance { get; } = new UnionCompletionItemComparer(); private UnionCompletionItemComparer() { } public bool Equals(CompletionItem x, CompletionItem y) { return x.DisplayText == y.DisplayText && (x.Tags == y.Tags || System.Linq.Enumerable.SequenceEqual(x.Tags, y.Tags)); } public int GetHashCode(CompletionItem obj) => Hash.Combine(obj.DisplayText.GetHashCode(), obj.Tags.Length); } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Compilers/CSharp/Test/Semantic/Semantics/BindingAwaitTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class BindingAwaitTests : CompilingTestBase { [WorkItem(547172, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547172")] [Fact, WorkItem(531516, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531516")] public void Bug18241() { var tree = SyntaxFactory.ParseSyntaxTree(" class C { void M() { await X() on "); SourceText text = tree.GetText(); TextSpan span = new TextSpan(text.Length, 0); TextChange change = new TextChange(span, "/*comment*/"); SourceText newText = text.WithChanges(change); // This line caused an assertion and then crashed in the parser. var newTree = tree.WithChangedText(newText); } [Fact] public void AwaitBadExpression() { var source = @" static class Program { static void Main() { } static async void f() { await goo; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (8,15): error CS0103: The name 'goo' does not exist in the current context // await goo; Diagnostic(ErrorCode.ERR_NameNotInContext, "goo").WithArguments("goo")); } [Fact] public void MissingGetAwaiterInstanceMethod() { var source = @" static class Program { static void Main() { } static async void f() { await new A(); } } class A { }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (8,9): error CS1061: 'A' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'A' could be found (are you missing a using directive or an assembly reference?) // await new A(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "await new A()").WithArguments("A", "GetAwaiter") ); } [Fact] public void InaccessibleGetAwaiterInstanceMethod() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); await new B(); await new C(); await new D(); } } class A { Awaiter GetAwaiter() { return new Awaiter(); } } class B { private Awaiter GetAwaiter() { return new Awaiter(); } } class C { protected Awaiter GetAwaiter() { return new Awaiter(); } } class D { public Awaiter GetAwaiter() { return new Awaiter(); } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0122: 'A.GetAwaiter()' is inaccessible due to its protection level // await new A(); Diagnostic(ErrorCode.ERR_BadAccess, "await new A()").WithArguments("A.GetAwaiter()"), // (11,9): error CS0122: 'B.GetAwaiter()' is inaccessible due to its protection level // await new B(); Diagnostic(ErrorCode.ERR_BadAccess, "await new B()").WithArguments("B.GetAwaiter()"), // (12,9): error CS0122: 'C.GetAwaiter()' is inaccessible due to its protection level // await new C(); Diagnostic(ErrorCode.ERR_BadAccess, "await new C()").WithArguments("C.GetAwaiter()") ); } [Fact] public void StaticGetAwaiterMethod() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); await new B(); } } class A { public Awaiter GetAwaiter() { return new Awaiter(); } } class B { public static Awaiter GetAwaiter() { return new Awaiter(); } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (11,9): error CS1986: 'await' requires that the type B have a suitable GetAwaiter method // await new B(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new B()").WithArguments("B") ); } [Fact] public void GetAwaiterFieldOrProperty() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); await new B(null); } } class A { Awaiter GetAwaiter { get { return new Awaiter(); } } } class B { public Awaiter GetAwaiter; public B(Awaiter getAwaiter) { this.GetAwaiter = getAwaiter; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS1955: Non-invocable member 'A.GetAwaiter' cannot be used like a method. // await new A(); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "await new A()").WithArguments("A.GetAwaiter"), // (11,9): error CS1955: Non-invocable member 'B.GetAwaiter' cannot be used like a method. // await new B(null); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "await new B(null)").WithArguments("B.GetAwaiter") ); } [Fact] public void GetAwaiterParams() { var source = @" using System; public class A { public Awaiter GetAwaiter(params object[] xs) { throw new Exception(); } } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class Test { static async void F() { await new A(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (22,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A")); } [Fact] public void VoidReturningGetAwaiterMethod() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public void GetAwaiter() { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A")); } [Fact] public void InaccessibleGetAwaiterExtensionMethod() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); await new B(); await new C(); } } class A { } class B { } class C { } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } static class MyExtensions { static Awaiter GetAwaiter(this A a) { return new Awaiter(); } private static Awaiter GetAwaiter(this B a) { return new Awaiter(); } public static Awaiter GetAwaiter(this C a) { return new Awaiter(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,15): error CS1929: 'A' does not contain a definition for 'GetAwaiter' and the best extension method overload 'MyExtensions.GetAwaiter(C)' requires a receiver of type 'C' // await new A(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "new A()").WithArguments("A", "GetAwaiter", "MyExtensions.GetAwaiter(C)", "C"), // (11,15): error CS1929: 'B' does not contain a definition for 'GetAwaiter' and the best extension method overload 'MyExtensions.GetAwaiter(C)' requires a receiver of type 'C' // await new B(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "new B()").WithArguments("B", "GetAwaiter", "MyExtensions.GetAwaiter(C)", "C") ); } [Fact] public void GetAwaiterExtensionMethodLookup() { var source = @" using System; class A { } class B { } class C { } static class Test { static async void F() { new A().GetAwaiter(); new B().GetAwaiter(); new C().GetAwaiter(); await new A(); await new B(); await new C(); } static Awaiter GetAwaiter(this A a) { throw new Exception(); } static void GetAwaiter(this B a) { throw new Exception(); } } static class E { public static void GetAwaiter(this A a) { throw new Exception(); } public static Awaiter GetAwaiter(this B a) { throw new Exception(); } public static Awaiter GetAwaiter(this C a) { throw new Exception(); } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (14,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(A)' and 'E.GetAwaiter(A)' // new A().GetAwaiter(); Diagnostic(ErrorCode.ERR_AmbigCall, "GetAwaiter").WithArguments("Test.GetAwaiter(A)", "E.GetAwaiter(A)"), // (15,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(B)' and 'E.GetAwaiter(B)' // new B().GetAwaiter(); Diagnostic(ErrorCode.ERR_AmbigCall, "GetAwaiter").WithArguments("Test.GetAwaiter(B)", "E.GetAwaiter(B)"), // (18,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(A)' and 'E.GetAwaiter(A)' // await new A(); Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("Test.GetAwaiter(A)", "E.GetAwaiter(A)"), // (19,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(B)' and 'E.GetAwaiter(B)' // await new B(); Diagnostic(ErrorCode.ERR_AmbigCall, "await new B()").WithArguments("Test.GetAwaiter(B)", "E.GetAwaiter(B)") ); } [Fact] public void ExtensionDuellingLookup() { var source = @" using System; public interface I1 { } public interface I2 { } public class A : I1, I2 { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class E { public static Awaiter GetAwaiter(this I1 a) { throw new Exception(); } public static Awaiter GetAwaiter(this I2 a) { throw new Exception(); } } public static class Test { static async void F() { await new A(); } static void Main() { F(); } public static void GetAwaiter(this I1 a) { throw new Exception(); } public static Awaiter GetAwaiter(this I2 a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (31,9): error CS0121: The call is ambiguous between the following methods or properties: 'E.GetAwaiter(I1)' and 'E.GetAwaiter(I2)' // await new A(); Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("E.GetAwaiter(I1)", "E.GetAwaiter(I2)") ); } [Fact] public void ExtensionDuellingMoreDerivedMoreOptional() { var source = @" using System; public interface I1 { } public interface I2 { } public class A : I1, I2 { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class Test { static async void F() { await new A(); } static void Main() { F(); } public static Awaiter GetAwaiter(this I1 a) { throw new Exception(); } public static Awaiter GetAwaiter(this A a, object o = null) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (19,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A")); } [Fact] public void ExtensionDuellingLessDerivedLessOptional() { var source = @" using System; public interface I1 { } public interface I2 { } public class A : I1, I2 { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class Test { static async void F() { await new A(); } static void Main() { F(); } public static void GetAwaiter(this A a, object o = null) { throw new Exception(); } public static Awaiter GetAwaiter(this I1 a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (19,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A")); } [Fact] public void ExtensionSiblingLookupOnExtraOptionalParam() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class Test { static async void F() { await new A(); } public static void GetAwaiter(this A a, object o = null) { throw new Exception(); } } public static class E { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact] public void ExtensionSiblingLookupOnVoidReturn() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class Test { static async void F() { await new A(); } public static void GetAwaiter(this A a) { throw new Exception(); } } public static class E { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (19,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(A)' and 'E.GetAwaiter(A)' // await new A(); Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("Test.GetAwaiter(A)", "E.GetAwaiter(A)")); } [Fact] public void ExtensionSiblingLookupOnInapplicable() { var source = @" using System; public class A { } public class B { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class Test { static async void F() { await new A(); } public static void GetAwaiter(this B a) { throw new Exception(); } } public static class E { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact] public void ExtensionSiblingLookupOnOptional() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class Test { static async void F() { await new A(); } public static Awaiter GetAwaiter(this object a, object o = null) { throw new Exception(); } } public static class E { public static void GetAwaiter(this object a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (24,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A")); } [Fact] public void ExtensionSiblingDuellingLookupOne() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class Test { static async void F() { await new A(); } static void Main() { F(); } } public static class E1 { public static void GetAwaiter(this A a) { throw new Exception(); } } public static class E2 { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (20,9): error CS0121: The call is ambiguous between the following methods or properties: 'E1.GetAwaiter(A)' and 'E2.GetAwaiter(A)' // await new A(); Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("E1.GetAwaiter(A)", "E2.GetAwaiter(A)") ); } [Fact] public void ExtensionSiblingDuellingLookupTwo() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class Test { static async void F() { await new A(); } static void Main() { F(); } } public static class E1 { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } } public static class E2 { public static void GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (20,9): error CS0121: The call is ambiguous between the following methods or properties: 'E1.GetAwaiter(A)' and 'E2.GetAwaiter(A)' // await new A(); Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("E1.GetAwaiter(A)", "E2.GetAwaiter(A)") ); } [Fact] public void ExtensionSiblingLookupOnLessDerived() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class Test { static async void F() { await new A(); } public static void GetAwaiter(this object a) { throw new Exception(); } } public static class E { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact] public void ExtensionSiblingLookupOnEquallyDerived() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } static class Test { static void Main() { F(); } static async void F() { await new A(); } public static Awaiter GetAwaiter(this object a) { throw new Exception(); } } public static class EE { public static void GetAwaiter(this object a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (24,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(object)' and 'EE.GetAwaiter(object)' // await new A(); Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("Test.GetAwaiter(object)", "EE.GetAwaiter(object)") ); } [Fact] public void ExtensionSiblingBadLookupOnEquallyDerived() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } static class Test { static void Main() { F(); } static async void F() { await new A(); } public static void GetAwaiter(this object a) { throw new Exception(); } } public static class EE { public static Awaiter GetAwaiter(this object a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (24,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(object)' and 'EE.GetAwaiter(object)' // await new A(); Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("Test.GetAwaiter(object)", "EE.GetAwaiter(object)") ); } [Fact] public void ExtensionParentNamespaceLookupOnOnReturnTypeMismatch() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } namespace parent { namespace child { static class Test { static async void F() { await new A(); } public static void GetAwaiter(this A a) { throw new Exception(); } } } public static class E { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (24,17): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A")); } [Fact] public void ExtensionParentNamespaceLookupOnOnInapplicableCandidate() { var source = @" using System; public class A { } public class B { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } namespace parent { namespace child { static class Test { static async void F() { await new A(); } public static void GetAwaiter(this B a) { throw new Exception(); } } } public static class E { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact] public void ExtensionParentNamespaceLookupOnOptional() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } namespace parent { namespace child { static class Test { static void Main() { F(); } static async void F() { await new A(); } public static Awaiter GetAwaiter(this A a, object o = null) { throw new Exception(); } } } public static class EE { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (11,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A")); } [Fact] public void ExtensionParentNamespaceLookupOnLessDerived() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } namespace parent { namespace child { static class Test { static void Main() { F(); } static async void F() { await new A(); } public static void GetAwaiter(this object a) { throw new Exception(); } } } public static class EE { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (11,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A")); } [Fact] public void ExtensionParentNamespaceDuellingLookupBad() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } namespace child { public static class Test { static async void F() { await new A(); } static void Main() { F(); } } } public static class E1 { public static void GetAwaiter(this A a) { throw new Exception(); } } public static class E2 { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (23,13): error CS0121: The call is ambiguous between the following methods or properties: 'E1.GetAwaiter(A)' and 'E2.GetAwaiter(A)' // await new A(); Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("E1.GetAwaiter(A)", "E2.GetAwaiter(A)") ); } [Fact] public void ExtensionParentNamespaceDuellingLookupWasGoodNowBad() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } namespace child { public static class Test { static async void F() { await new A(); } static void Main() { F(); } } } public static class E1 { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } } public static class E2 { public static void GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (23,13): error CS0121: The call is ambiguous between the following methods or properties: 'E1.GetAwaiter(A)' and 'E2.GetAwaiter(A)' // await new A(); Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("E1.GetAwaiter(A)", "E2.GetAwaiter(A)") ); } [Fact] public void ExtensionParentNamespaceSingleClassDuel() { var source = @" using System; public interface I1 { } public interface I2 { } public class A : I1, I2 { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } namespace parent { namespace child { public static class Test { static async void F() { await new A(); } static void Main() { F(); } } } } public static class E2 { public static void GetAwaiter(this I1 a) { throw new Exception(); } public static Awaiter GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact] public void TruncateExtensionMethodLookupAfterFirstNamespace() { var source = @" using System; public interface I1 { } public interface I2 { } public class A : I1, I2 { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } namespace parent { namespace child { public static class Test { public static void Main() { F(); } static async void F() { await new A(); } public static void GetAwaiter(this I1 a) { throw new Exception(); } } public static class E { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } } } } public static class E2 { public static void GetAwaiter(this I1 a) { throw new Exception(); } public static Awaiter GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact] public void BadTruncateExtensionMethodLookupAfterFirstNamespace() { var source = @" using System; public interface I1 { } public interface I2 { } public class A : I1, I2 { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } namespace parent { namespace child { public static class Test { public static void Main() { F(); } static async void F() { await new A(); } public static void GetAwaiter(this I1 a) { throw new Exception(); } } } public static class E { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } } } public static class E2 { public static void GetAwaiter(this I1 a) { throw new Exception(); } public static Awaiter GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (11,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A")); } [Fact] public void FallbackToGetAwaiterExtensionMethod() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { private Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } static class MyExtensions { public static Awaiter GetAwaiter(this A a) { return new Awaiter(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact] public void BadFallbackToGetAwaiterExtensionMethodInPresenceOfInstanceGetAwaiterMethodWithOptionalParameter() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter(object o = null) { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } static class MyExtensions { public static Awaiter GetAwaiter(this A a) { return new Awaiter(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A")); } [Fact] public void GetAwaiterMethodWithNonZeroArity() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); await new B(); await new C(); await new D(); await new E(); } } class A { public Awaiter GetAwaiter(object o = null) { return null; } } class B { public Awaiter GetAwaiter(object o) { return null; } } class C { } class D { } class E { public Awaiter GetAwaiter() { return null; } public Awaiter GetAwaiter(object o = null) { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } static class MyExtensions { public static Awaiter GetAwaiter(this C a, object o = null) { return new Awaiter(); } public static Awaiter GetAwaiter(this D a, object o) { return new Awaiter(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A").WithLocation(10, 9), // (11,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'o' of 'B.GetAwaiter(object)' // await new B(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "await new B()").WithArguments("o", "B.GetAwaiter(object)").WithLocation(11, 9), // (12,9): error CS1986: 'await' requires that the type C have a suitable GetAwaiter method // await new C(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new C()").WithArguments("C").WithLocation(12, 9), // (13,15): error CS1929: 'D' does not contain a definition for 'GetAwaiter' and the best extension method overload 'MyExtensions.GetAwaiter(C, object)' requires a receiver of type 'C' // await new D(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "new D()").WithArguments("D", "GetAwaiter", "MyExtensions.GetAwaiter(C, object)", "C").WithLocation(13, 15)); } [Fact] public void GetAwaiterMethodWithNonZeroTypeParameterArity() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); await new B(); } } class A { public Awaiter GetAwaiter<T>() { return null; } } class B { } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } static class MyExtensions { public static Awaiter GetAwaiter<T>(this B a) { return null; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'A.GetAwaiter<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly. // await new A(); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "await new A()").WithArguments("A.GetAwaiter<T>()"), // (11,9): error CS0411: The type arguments for method 'MyExtensions.GetAwaiter<T>(B)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // await new B(); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "await new B()").WithArguments("MyExtensions.GetAwaiter<T>(B)") ); } [Fact] public void AwaiterImplementsINotifyCompletion() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); await new B(); await new C(); await new D(); } } class A { public Awaiter1 GetAwaiter() { return null; } } class B { public Awaiter2 GetAwaiter() { return null; } } class C { public Awaiter3 GetAwaiter() { return null; } } class D { public Awaiter4 GetAwaiter() { return null; } } class Awaiter1 : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } class OnCompletedImpl : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } } class Awaiter2 : OnCompletedImpl { public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } interface OnCompletedInterface : System.Runtime.CompilerServices.INotifyCompletion { } class Awaiter3 : OnCompletedInterface { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } class Awaiter4 { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (13,9): error CS4027: 'Awaiter4' does not implement 'System.Runtime.CompilerServices.INotifyCompletion' // await new D(); Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new D()").WithArguments("Awaiter4", "System.Runtime.CompilerServices.INotifyCompletion")); } [WorkItem(770448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770448")] [Fact] public void AwaiterImplementsINotifyCompletion_Constraint() { var source = @"using System.Runtime.CompilerServices; class Awaitable<T> { internal T GetAwaiter() { return default(T); } } interface IA { bool IsCompleted { get; } object GetResult(); } interface IB : IA, INotifyCompletion { } class A { public void OnCompleted(System.Action a) { } internal bool IsCompleted { get { return true; } } internal object GetResult() { return null; } } class B : A, INotifyCompletion { } class C { static async void F<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>() where T1 : IA where T2 : IA, INotifyCompletion where T3 : IB where T4 : T1, INotifyCompletion where T5 : T3 where T6 : A where T7 : A, INotifyCompletion where T8 : B where T9 : T6, INotifyCompletion where T10 : T8 { await new Awaitable<T1>(); await new Awaitable<T2>(); await new Awaitable<T3>(); await new Awaitable<T4>(); await new Awaitable<T5>(); await new Awaitable<T6>(); await new Awaitable<T7>(); await new Awaitable<T8>(); await new Awaitable<T9>(); await new Awaitable<T10>(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (37,9): error CS4027: 'T1' does not implement 'System.Runtime.CompilerServices.INotifyCompletion' // await new Awaitable<T1>(); Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<T1>()").WithArguments("T1", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(37, 9), // (42,9): error CS4027: 'T6' does not implement 'System.Runtime.CompilerServices.INotifyCompletion' // await new Awaitable<T6>(); Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<T6>()").WithArguments("T6", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(42, 9)); } [WorkItem(770448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770448")] [Fact] public void AwaiterImplementsINotifyCompletion_InheritedConstraint() { var source = @"using System; using System.Runtime.CompilerServices; class Awaitable<T> { internal T GetAwaiter() { return default(T); } } interface IA { bool IsCompleted { get; } object GetResult(); } interface IB : IA, INotifyCompletion { } class B : IA, INotifyCompletion { public void OnCompleted(Action a) { } public bool IsCompleted { get { return true; } } public object GetResult() { return null; } } struct S : IA, INotifyCompletion { public void OnCompleted(Action a) { } public bool IsCompleted { get { return true; } } public object GetResult() { return null; } } class C<T> where T : IA { internal virtual async void F<U>() where U : T { await new Awaitable<U>(); } } class D1 : C<IB> { internal override async void F<T1>() { await new Awaitable<T1>(); } } class D2 : C<B> { internal override async void F<T2>() { await new Awaitable<T2>(); } } class D3 : C<S> { internal override async void F<T3>() { await new Awaitable<T3>(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (31,9): error CS4027: 'U' does not implement 'System.Runtime.CompilerServices.INotifyCompletion' // await new Awaitable<U>(); Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<U>()").WithArguments("U", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(31, 9), // (52,9): error CS0117: 'T3' does not contain a definition for 'IsCompleted' // await new Awaitable<T3>(); Diagnostic(ErrorCode.ERR_NoSuchMember, "await new Awaitable<T3>()").WithArguments("T3", "IsCompleted").WithLocation(52, 9)); } [WorkItem(770448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770448")] [Fact] public void AwaiterImplementsINotifyCompletion_UserDefinedConversion() { var source = @"using System; using System.Runtime.CompilerServices; class Awaitable<T> { internal T GetAwaiter() { return default(T); } } interface IA : INotifyCompletion { bool IsCompleted { get; } object GetResult(); } class A : INotifyCompletion { public void OnCompleted(Action a) { } public bool IsCompleted { get { return true; } } public object GetResult() { return null; } } class B { public void OnCompleted(Action a) { } public bool IsCompleted { get { return true; } } public static implicit operator A(B b) { return default(A); } } class B<T> where T : INotifyCompletion { public void OnCompleted(Action a) { } public bool IsCompleted { get { return true; } } public static implicit operator T(B<T> b) { return default(T); } } class C { async void F() { await new Awaitable<B>(); await new Awaitable<B<IA>>(); await new Awaitable<B<A>>(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (34,9): error CS4027: 'B' does not implement 'System.Runtime.CompilerServices.INotifyCompletion' // await new Awaitable<B>(); Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<B>()").WithArguments("B", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(34, 9), // (35,9): error CS4027: 'B<IA>' does not implement 'System.Runtime.CompilerServices.INotifyCompletion' // await new Awaitable<B<IA>>(); Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<B<IA>>()").WithArguments("B<IA>", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(35, 9), // (36,9): error CS4027: 'B<A>' does not implement 'System.Runtime.CompilerServices.INotifyCompletion' // await new Awaitable<B<A>>(); Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<B<A>>()").WithArguments("B<A>", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(36, 9)); } /// <summary> /// Should call ICriticalNotifyCompletion.UnsafeOnCompleted /// if the awaiter type implements ICriticalNotifyCompletion. /// </summary> [Fact] public void AwaiterImplementsICriticalNotifyCompletion_Constraint() { var source = @"using System; using System.Runtime.CompilerServices; class Awaitable<T> { internal T GetAwaiter() { return default(T); } } class A : INotifyCompletion { public void OnCompleted(Action a) { } public bool IsCompleted { get { return true; } } public object GetResult() { return null; } } class B : A, ICriticalNotifyCompletion { public void UnsafeOnCompleted(Action a) { } } class C { static async void F<T1, T2, T3, T4, T5, T6>() where T1 : A where T2 : A, ICriticalNotifyCompletion where T3 : B where T4 : T1 where T5 : T2 where T6 : T1, ICriticalNotifyCompletion { await new Awaitable<T1>(); await new Awaitable<T2>(); await new Awaitable<T3>(); await new Awaitable<T4>(); await new Awaitable<T5>(); await new Awaitable<T6>(); } }"; var compilation = CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); var verifier = CompileAndVerify(compilation); var actualIL = verifier.VisualizeIL("C.<F>d__0<T1, T2, T3, T4, T5, T6>.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()"); var calls = actualIL.Split(new[] { '\n', '\r' }, System.StringSplitOptions.RemoveEmptyEntries).Where(s => s.Contains("OnCompleted")).ToArray(); Assert.Equal(6, calls.Length); Assert.Equal(" IL_0056: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitOnCompleted<T1, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T1, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[0]); Assert.Equal(" IL_00b9: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<T2, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T2, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[1]); Assert.Equal(" IL_011c: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<T3, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T3, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[2]); Assert.Equal(" IL_0182: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitOnCompleted<T4, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T4, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[3]); Assert.Equal(" IL_01ea: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<T5, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T5, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[4]); Assert.Equal(" IL_0252: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<T6, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T6, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[5]); } [Fact] public void ConditionalOnCompletedImplementation() { var source = @" using System; using System.Diagnostics; static class Program { static void Main() { } static async void f() { await new A(); await new B(); } } class A { public Awaiter GetAwaiter() { return null; } } class B { } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { [Conditional(""Condition"")] public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } static class MyExtensions { public static Awaiter GetAwaiter(this B a) { return null; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (28,17): error CS0629: Conditional member 'Awaiter.OnCompleted(System.Action)' cannot implement interface member 'System.Runtime.CompilerServices.INotifyCompletion.OnCompleted(System.Action)' in type 'Awaiter' // public void OnCompleted(Action x) { } Diagnostic(ErrorCode.ERR_InterfaceImplementedByConditional, "OnCompleted").WithArguments("Awaiter.OnCompleted(System.Action)", "System.Runtime.CompilerServices.INotifyCompletion.OnCompleted(System.Action)", "Awaiter")); } [Fact] public void MissingIsCompletedProperty() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0117: 'Awaiter' does not contain a definition for 'IsCompleted' // await new A(); Diagnostic(ErrorCode.ERR_NoSuchMember, "await new A()").WithArguments("Awaiter", "IsCompleted")); } [Fact] public void InaccessibleIsCompletedProperty() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } bool IsCompleted { get { return false; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0117: 'Awaiter' does not contain a definition for 'IsCompleted' // await new A(); Diagnostic(ErrorCode.ERR_NoSuchMember, "await new A()").WithArguments("Awaiter", "IsCompleted")); } [Fact] public void StaticIsCompletedProperty() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public static bool IsCompleted { get { return false; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0176: Member 'Awaiter.IsCompleted' cannot be accessed with an instance reference; qualify it with a type name instead // await new A(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "await new A()").WithArguments("Awaiter.IsCompleted") ); } [Fact] public void StaticWriteonlyIsCompletedProperty() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public static bool IsCompleted { set { } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0176: Member 'Awaiter.IsCompleted' cannot be accessed with an instance reference; qualify it with a type name instead // await new A(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "await new A()").WithArguments("Awaiter.IsCompleted") ); } [Fact] public void StaticAccessorlessIsCompletedProperty() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public static bool IsCompleted { } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (25,24): error CS0548: 'Awaiter.IsCompleted': property or indexer must have at least one accessor // public static bool IsCompleted { } Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "IsCompleted").WithArguments("Awaiter.IsCompleted"), // (10,9): error CS0176: Member 'Awaiter.IsCompleted' cannot be accessed with an instance reference; qualify it with a type name instead // await new A(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "await new A()").WithArguments("Awaiter.IsCompleted") ); } [Fact] public void NonBooleanIsCompletedProperty() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public int IsCompleted { get { return -1; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS4011: 'await' requires that the return type 'Awaiter' of 'A.GetAwaiter()' have suitable IsCompleted, OnCompleted, and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion // await new A(); Diagnostic(ErrorCode.ERR_BadAwaiterPattern, "await new A()").WithArguments("Awaiter", "A")); } [Fact] public void WriteonlyIsCompletedProperty() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { set { } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0117: 'A' does not contain a definition for 'IsCompleted' // await new A(); Diagnostic(ErrorCode.ERR_PropertyLacksGet, "await new A()").WithArguments("Awaiter.IsCompleted")); } [Fact] public void WriteonlyNonBooleanIsCompletedProperty() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public int IsCompleted { set { } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0117: 'A' does not contain a definition for 'IsCompleted' // await new A(); Diagnostic(ErrorCode.ERR_PropertyLacksGet, "await new A()").WithArguments("Awaiter.IsCompleted")); } [Fact] public void MissingGetResultInstanceMethod() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool IsCompleted { get { return false; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0117: 'Awaiter' does not contain a definition for 'GetResult' // await new A(); Diagnostic(ErrorCode.ERR_NoSuchMember, "await new A()").WithArguments("Awaiter", "GetResult")); } [Fact] public void InaccessibleGetResultInstanceMethod() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } private bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return false; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0122: 'Awaiter.GetResult()' is inaccessible due to its protection level // await new A(); Diagnostic(ErrorCode.ERR_BadAccess, "await new A()").WithArguments("Awaiter.GetResult()") ); } [Fact] public void StaticResultMethod() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public static bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return false; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0176: Member 'Awaiter.GetResult()' cannot be accessed with an instance reference; qualify it with a type name instead // await new A(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "await new A()").WithArguments("Awaiter.GetResult()")); } [Fact] public void GetResultExtensionMethod() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool IsCompleted { get { return false; } } } static class MyExtensions { public static bool GetResult(this Awaiter a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0117: 'Awaiter' does not contain a definition for 'GetResult' // await new A(); Diagnostic(ErrorCode.ERR_NoSuchMember, "await new A()").WithArguments("Awaiter", "GetResult")); } [Fact] public void GetResultWithNonZeroArity() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult(object o = null) { throw new Exception(); } public bool IsCompleted { get { return false; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS4011: 'await' requires that the return type 'Awaiter' of 'A.GetAwaiter()' have suitable IsCompleted, OnCompleted, and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion // await new A(); Diagnostic(ErrorCode.ERR_BadAwaiterPattern, "await new A()").WithArguments("Awaiter", "A")); } [Fact] public void GetResultWithNonZeroTypeParameterArity() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult<T>() { throw new Exception(); } public bool IsCompleted { get { return false; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'Awaiter.GetResult<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly. // await new A(); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "await new A()").WithArguments("Awaiter.GetResult<T>()") ); } [Fact] public void ConditionalGetResult() { var source = @" using System; using System.Diagnostics; static class Program { static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return new Awaiter(); } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } [Conditional(""X"")] public void GetResult() { Console.WriteLine(""unconditional""); } public bool IsCompleted { get { return true; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (15,9): error CS4011: 'await' requires that the return type 'Awaiter' of 'A.GetAwaiter()' have suitable IsCompleted, OnCompleted, and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion // await new A(); Diagnostic(ErrorCode.ERR_BadAwaiterPattern, "await new A()").WithArguments("Awaiter", "A")); } [Fact] public void Missing_IsCompleted_INotifyCompletion_GetResult() { var source = @" static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter //: System.Runtime.CompilerServices.INotifyCompletion { //public void OnCompleted(Action x) { } //public bool GetResult() { throw new Exception(); } //public bool IsCompleted { get { return true; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (8,9): error CS0117: 'Awaiter' does not contain a definition for 'IsCompleted' // await new A(); Diagnostic(ErrorCode.ERR_NoSuchMember, "await new A()").WithArguments("Awaiter", "IsCompleted")); } [Fact] public void Missing_INotifyCompletion_GetResult() { var source = @" static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter //: System.Runtime.CompilerServices.INotifyCompletion { //public void OnCompleted(Action x) { } //public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (8,9): error CS4027: 'Awaiter' does not implement 'System.Runtime.CompilerServices.INotifyCompletion' // await new A(); Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new A()").WithArguments("Awaiter", "System.Runtime.CompilerServices.INotifyCompletion")); } [Fact] public void BadAwaitArg_NeedSystem() { var source = @" // using System; using System.Threading.Tasks; using Windows.Devices.Enumeration; class App { static void Main() { EnumDevices().Wait(); } private static async Task EnumDevices() { await DeviceInformation.FindAllAsync(); return; } }"; CreateCompilationWithWinRT(source).VerifyDiagnostics( // (12,9): error CS4035: 'Windows.Foundation.IAsyncOperation<Windows.Devices.Enumeration.DeviceInformationCollection>' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'Windows.Foundation.IAsyncOperation<Windows.Devices.Enumeration.DeviceInformationCollection>' could be found (are you missing a using directive for 'System'?) // await DeviceInformation.FindAllAsync(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtensionNeedUsing, "await DeviceInformation.FindAllAsync()").WithArguments("Windows.Foundation.IAsyncOperation<Windows.Devices.Enumeration.DeviceInformationCollection>", "GetAwaiter", "System") ); } [Fact] public void ErrorInAwaitSubexpression() { var source = @" class C { async void M() { using (await goo()) { } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,22): error CS0103: The name 'goo' does not exist in the current context // using (await goo()) Diagnostic(ErrorCode.ERR_NameNotInContext, "goo").WithArguments("goo")); } [Fact] public void BadAwaitArgIntrinsic() { var source = @" class Test { public void goo() { } public async void awaitVoid() { await goo(); } public async void awaitNull() { await null; } public async void awaitMethodGroup() { await goo; } public async void awaitLambda() { await (x => x); } public static void Main() { } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (8,9): error CS4008: Cannot await 'void' // await goo(); Diagnostic(ErrorCode.ERR_BadAwaitArgVoidCall, "await goo()"), // (13,9): error CS4001: Cannot await '<null>;' // await null; Diagnostic(ErrorCode.ERR_BadAwaitArgIntrinsic, "await null").WithArguments("<null>"), // (18,9): error CS4001: Cannot await 'method group' // await goo; Diagnostic(ErrorCode.ERR_BadAwaitArgIntrinsic, "await goo").WithArguments("method group"), // (23,9): error CS4001: Cannot await 'lambda expression' // await (x => x); Diagnostic(ErrorCode.ERR_BadAwaitArgIntrinsic, "await (x => x)").WithArguments("lambda expression")); } [Fact] public void BadAwaitArgVoidCall() { var source = @" using System.Threading.Tasks; class Test { public async void goo() { await Task.Factory.StartNew(() => { }); } public async void bar() { await goo(); } public static void Main() { } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS4008: Cannot await 'void' // await goo(); Diagnostic(ErrorCode.ERR_BadAwaitArgVoidCall, "await goo()")); } [Fact, WorkItem(531356, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531356")] public void Repro_17997() { var source = @" class C { public IVsTask ResolveReferenceAsync() { return this.VsTasksService.InvokeAsync(async delegate { return null; }); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (4,12): error CS0246: The type or namespace name 'IVsTask' could not be found (are you missing a using directive or an assembly reference?) // public IVsTask ResolveReferenceAsync() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IVsTask").WithArguments("IVsTask").WithLocation(4, 12), // (6,21): error CS1061: 'C' does not contain a definition for 'VsTasksService' and no extension method 'VsTasksService' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // return this.VsTasksService.InvokeAsync(async delegate Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "VsTasksService").WithArguments("C", "VsTasksService").WithLocation(6, 21), // (6,54): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // return this.VsTasksService.InvokeAsync(async delegate Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "delegate").WithLocation(6, 54)); } [Fact, WorkItem(627123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627123")] public void Repro_627123() { var source = @" using System; using System.Runtime.CompilerServices; interface IA : INotifyCompletion { bool IsCompleted { get; } void GetResult(); } interface IB : IA { new Action GetResult { get; } } interface IC { IB GetAwaiter(); } class D { Action<IC> a = async x => await x; }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (23,31): error CS0118: 'GetResult' is a property but is used like a method // Action<IC> a = async x => await x; Diagnostic(ErrorCode.ERR_BadSKknown, "await x").WithArguments("GetResult", "property", "method") ); } [Fact, WorkItem(1091911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091911")] public void Repro_1091911() { const string source = @" using System; using System.Threading.Tasks; class Repro { int Boom { get { return 42; } } static Task<dynamic> Compute() { return Task.FromResult<dynamic>(new Repro()); } static async Task<int> Bug() { dynamic results = await Compute().ConfigureAwait(false); var x = results.Boom; return (int)x; } static void Main() { Console.WriteLine(Bug().Result); } }"; var comp = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [Fact] public void DynamicResultTypeCustomAwaiter() { const string source = @" using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; public struct MyTask { public readonly Task task; private readonly Func<dynamic> getResult; public MyTask(Task task, Func<dynamic> getResult) { this.task = task; this.getResult = getResult; } public dynamic Result { get { return this.getResult(); } } } public struct MyAwaiter : INotifyCompletion { private readonly MyTask task; public MyAwaiter(MyTask task) { this.task = task; } public bool IsCompleted { get { return true; } } public dynamic GetResult() { Console.Write(""dynamic""); return task.Result; } public void OnCompleted(System.Action continuation) { task.task.ContinueWith(_ => continuation()); } } public static class TaskAwaiter { public static MyAwaiter GetAwaiter(this MyTask task) { return new MyAwaiter(task); } } class Repro { int Boom { get { return 42; } } static MyTask Compute() { var task = Task.FromResult(new Repro()); return new MyTask(task, () => task.Result); } static async Task<int> Bug() { return (await Compute()).Boom; } static void Main() { Console.WriteLine(Bug().Result); } } "; var comp = CreateCompilationWithMscorlib45(source, new[] { TestMetadata.Net40.SystemCore, TestMetadata.Net40.MicrosoftCSharp }, TestOptions.ReleaseExe); comp.VerifyDiagnostics( // warning CS1685: The predefined type 'ExtensionAttribute' is defined in multiple assemblies in the global alias; using definition from 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Diagnostic(ErrorCode.WRN_MultiplePredefTypes).WithArguments("System.Runtime.CompilerServices.ExtensionAttribute", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").WithLocation(1, 1)); var compiled = CompileAndVerify(comp, expectedOutput: "dynamic42", verify: Verification.Fails); compiled.VerifyIL("MyAwaiter.OnCompleted(System.Action)", @" { // Code size 43 (0x2b) .maxstack 3 .locals init (MyAwaiter.<>c__DisplayClass5_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""MyAwaiter.<>c__DisplayClass5_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.1 IL_0008: stfld ""System.Action MyAwaiter.<>c__DisplayClass5_0.continuation"" IL_000d: ldarg.0 IL_000e: ldflda ""MyTask MyAwaiter.task"" IL_0013: ldfld ""System.Threading.Tasks.Task MyTask.task"" IL_0018: ldloc.0 IL_0019: ldftn ""void MyAwaiter.<>c__DisplayClass5_0.<OnCompleted>b__0(System.Threading.Tasks.Task)"" IL_001f: newobj ""System.Action<System.Threading.Tasks.Task>..ctor(object, System.IntPtr)"" IL_0024: callvirt ""System.Threading.Tasks.Task System.Threading.Tasks.Task.ContinueWith(System.Action<System.Threading.Tasks.Task>)"" IL_0029: pop IL_002a: ret }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class BindingAwaitTests : CompilingTestBase { [WorkItem(547172, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547172")] [Fact, WorkItem(531516, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531516")] public void Bug18241() { var tree = SyntaxFactory.ParseSyntaxTree(" class C { void M() { await X() on "); SourceText text = tree.GetText(); TextSpan span = new TextSpan(text.Length, 0); TextChange change = new TextChange(span, "/*comment*/"); SourceText newText = text.WithChanges(change); // This line caused an assertion and then crashed in the parser. var newTree = tree.WithChangedText(newText); } [Fact] public void AwaitBadExpression() { var source = @" static class Program { static void Main() { } static async void f() { await goo; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (8,15): error CS0103: The name 'goo' does not exist in the current context // await goo; Diagnostic(ErrorCode.ERR_NameNotInContext, "goo").WithArguments("goo")); } [Fact] public void MissingGetAwaiterInstanceMethod() { var source = @" static class Program { static void Main() { } static async void f() { await new A(); } } class A { }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (8,9): error CS1061: 'A' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'A' could be found (are you missing a using directive or an assembly reference?) // await new A(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "await new A()").WithArguments("A", "GetAwaiter") ); } [Fact] public void InaccessibleGetAwaiterInstanceMethod() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); await new B(); await new C(); await new D(); } } class A { Awaiter GetAwaiter() { return new Awaiter(); } } class B { private Awaiter GetAwaiter() { return new Awaiter(); } } class C { protected Awaiter GetAwaiter() { return new Awaiter(); } } class D { public Awaiter GetAwaiter() { return new Awaiter(); } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0122: 'A.GetAwaiter()' is inaccessible due to its protection level // await new A(); Diagnostic(ErrorCode.ERR_BadAccess, "await new A()").WithArguments("A.GetAwaiter()"), // (11,9): error CS0122: 'B.GetAwaiter()' is inaccessible due to its protection level // await new B(); Diagnostic(ErrorCode.ERR_BadAccess, "await new B()").WithArguments("B.GetAwaiter()"), // (12,9): error CS0122: 'C.GetAwaiter()' is inaccessible due to its protection level // await new C(); Diagnostic(ErrorCode.ERR_BadAccess, "await new C()").WithArguments("C.GetAwaiter()") ); } [Fact] public void StaticGetAwaiterMethod() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); await new B(); } } class A { public Awaiter GetAwaiter() { return new Awaiter(); } } class B { public static Awaiter GetAwaiter() { return new Awaiter(); } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (11,9): error CS1986: 'await' requires that the type B have a suitable GetAwaiter method // await new B(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new B()").WithArguments("B") ); } [Fact] public void GetAwaiterFieldOrProperty() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); await new B(null); } } class A { Awaiter GetAwaiter { get { return new Awaiter(); } } } class B { public Awaiter GetAwaiter; public B(Awaiter getAwaiter) { this.GetAwaiter = getAwaiter; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS1955: Non-invocable member 'A.GetAwaiter' cannot be used like a method. // await new A(); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "await new A()").WithArguments("A.GetAwaiter"), // (11,9): error CS1955: Non-invocable member 'B.GetAwaiter' cannot be used like a method. // await new B(null); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "await new B(null)").WithArguments("B.GetAwaiter") ); } [Fact] public void GetAwaiterParams() { var source = @" using System; public class A { public Awaiter GetAwaiter(params object[] xs) { throw new Exception(); } } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class Test { static async void F() { await new A(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (22,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A")); } [Fact] public void VoidReturningGetAwaiterMethod() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public void GetAwaiter() { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A")); } [Fact] public void InaccessibleGetAwaiterExtensionMethod() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); await new B(); await new C(); } } class A { } class B { } class C { } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } static class MyExtensions { static Awaiter GetAwaiter(this A a) { return new Awaiter(); } private static Awaiter GetAwaiter(this B a) { return new Awaiter(); } public static Awaiter GetAwaiter(this C a) { return new Awaiter(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,15): error CS1929: 'A' does not contain a definition for 'GetAwaiter' and the best extension method overload 'MyExtensions.GetAwaiter(C)' requires a receiver of type 'C' // await new A(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "new A()").WithArguments("A", "GetAwaiter", "MyExtensions.GetAwaiter(C)", "C"), // (11,15): error CS1929: 'B' does not contain a definition for 'GetAwaiter' and the best extension method overload 'MyExtensions.GetAwaiter(C)' requires a receiver of type 'C' // await new B(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "new B()").WithArguments("B", "GetAwaiter", "MyExtensions.GetAwaiter(C)", "C") ); } [Fact] public void GetAwaiterExtensionMethodLookup() { var source = @" using System; class A { } class B { } class C { } static class Test { static async void F() { new A().GetAwaiter(); new B().GetAwaiter(); new C().GetAwaiter(); await new A(); await new B(); await new C(); } static Awaiter GetAwaiter(this A a) { throw new Exception(); } static void GetAwaiter(this B a) { throw new Exception(); } } static class E { public static void GetAwaiter(this A a) { throw new Exception(); } public static Awaiter GetAwaiter(this B a) { throw new Exception(); } public static Awaiter GetAwaiter(this C a) { throw new Exception(); } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (14,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(A)' and 'E.GetAwaiter(A)' // new A().GetAwaiter(); Diagnostic(ErrorCode.ERR_AmbigCall, "GetAwaiter").WithArguments("Test.GetAwaiter(A)", "E.GetAwaiter(A)"), // (15,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(B)' and 'E.GetAwaiter(B)' // new B().GetAwaiter(); Diagnostic(ErrorCode.ERR_AmbigCall, "GetAwaiter").WithArguments("Test.GetAwaiter(B)", "E.GetAwaiter(B)"), // (18,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(A)' and 'E.GetAwaiter(A)' // await new A(); Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("Test.GetAwaiter(A)", "E.GetAwaiter(A)"), // (19,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(B)' and 'E.GetAwaiter(B)' // await new B(); Diagnostic(ErrorCode.ERR_AmbigCall, "await new B()").WithArguments("Test.GetAwaiter(B)", "E.GetAwaiter(B)") ); } [Fact] public void ExtensionDuellingLookup() { var source = @" using System; public interface I1 { } public interface I2 { } public class A : I1, I2 { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class E { public static Awaiter GetAwaiter(this I1 a) { throw new Exception(); } public static Awaiter GetAwaiter(this I2 a) { throw new Exception(); } } public static class Test { static async void F() { await new A(); } static void Main() { F(); } public static void GetAwaiter(this I1 a) { throw new Exception(); } public static Awaiter GetAwaiter(this I2 a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (31,9): error CS0121: The call is ambiguous between the following methods or properties: 'E.GetAwaiter(I1)' and 'E.GetAwaiter(I2)' // await new A(); Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("E.GetAwaiter(I1)", "E.GetAwaiter(I2)") ); } [Fact] public void ExtensionDuellingMoreDerivedMoreOptional() { var source = @" using System; public interface I1 { } public interface I2 { } public class A : I1, I2 { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class Test { static async void F() { await new A(); } static void Main() { F(); } public static Awaiter GetAwaiter(this I1 a) { throw new Exception(); } public static Awaiter GetAwaiter(this A a, object o = null) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (19,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A")); } [Fact] public void ExtensionDuellingLessDerivedLessOptional() { var source = @" using System; public interface I1 { } public interface I2 { } public class A : I1, I2 { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class Test { static async void F() { await new A(); } static void Main() { F(); } public static void GetAwaiter(this A a, object o = null) { throw new Exception(); } public static Awaiter GetAwaiter(this I1 a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (19,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A")); } [Fact] public void ExtensionSiblingLookupOnExtraOptionalParam() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class Test { static async void F() { await new A(); } public static void GetAwaiter(this A a, object o = null) { throw new Exception(); } } public static class E { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact] public void ExtensionSiblingLookupOnVoidReturn() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class Test { static async void F() { await new A(); } public static void GetAwaiter(this A a) { throw new Exception(); } } public static class E { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (19,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(A)' and 'E.GetAwaiter(A)' // await new A(); Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("Test.GetAwaiter(A)", "E.GetAwaiter(A)")); } [Fact] public void ExtensionSiblingLookupOnInapplicable() { var source = @" using System; public class A { } public class B { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class Test { static async void F() { await new A(); } public static void GetAwaiter(this B a) { throw new Exception(); } } public static class E { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact] public void ExtensionSiblingLookupOnOptional() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class Test { static async void F() { await new A(); } public static Awaiter GetAwaiter(this object a, object o = null) { throw new Exception(); } } public static class E { public static void GetAwaiter(this object a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (24,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A")); } [Fact] public void ExtensionSiblingDuellingLookupOne() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class Test { static async void F() { await new A(); } static void Main() { F(); } } public static class E1 { public static void GetAwaiter(this A a) { throw new Exception(); } } public static class E2 { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (20,9): error CS0121: The call is ambiguous between the following methods or properties: 'E1.GetAwaiter(A)' and 'E2.GetAwaiter(A)' // await new A(); Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("E1.GetAwaiter(A)", "E2.GetAwaiter(A)") ); } [Fact] public void ExtensionSiblingDuellingLookupTwo() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class Test { static async void F() { await new A(); } static void Main() { F(); } } public static class E1 { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } } public static class E2 { public static void GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (20,9): error CS0121: The call is ambiguous between the following methods or properties: 'E1.GetAwaiter(A)' and 'E2.GetAwaiter(A)' // await new A(); Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("E1.GetAwaiter(A)", "E2.GetAwaiter(A)") ); } [Fact] public void ExtensionSiblingLookupOnLessDerived() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } public static class Test { static async void F() { await new A(); } public static void GetAwaiter(this object a) { throw new Exception(); } } public static class E { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact] public void ExtensionSiblingLookupOnEquallyDerived() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } static class Test { static void Main() { F(); } static async void F() { await new A(); } public static Awaiter GetAwaiter(this object a) { throw new Exception(); } } public static class EE { public static void GetAwaiter(this object a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (24,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(object)' and 'EE.GetAwaiter(object)' // await new A(); Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("Test.GetAwaiter(object)", "EE.GetAwaiter(object)") ); } [Fact] public void ExtensionSiblingBadLookupOnEquallyDerived() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } static class Test { static void Main() { F(); } static async void F() { await new A(); } public static void GetAwaiter(this object a) { throw new Exception(); } } public static class EE { public static Awaiter GetAwaiter(this object a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (24,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(object)' and 'EE.GetAwaiter(object)' // await new A(); Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("Test.GetAwaiter(object)", "EE.GetAwaiter(object)") ); } [Fact] public void ExtensionParentNamespaceLookupOnOnReturnTypeMismatch() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } namespace parent { namespace child { static class Test { static async void F() { await new A(); } public static void GetAwaiter(this A a) { throw new Exception(); } } } public static class E { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (24,17): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A")); } [Fact] public void ExtensionParentNamespaceLookupOnOnInapplicableCandidate() { var source = @" using System; public class A { } public class B { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } namespace parent { namespace child { static class Test { static async void F() { await new A(); } public static void GetAwaiter(this B a) { throw new Exception(); } } } public static class E { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact] public void ExtensionParentNamespaceLookupOnOptional() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } namespace parent { namespace child { static class Test { static void Main() { F(); } static async void F() { await new A(); } public static Awaiter GetAwaiter(this A a, object o = null) { throw new Exception(); } } } public static class EE { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (11,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A")); } [Fact] public void ExtensionParentNamespaceLookupOnLessDerived() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } namespace parent { namespace child { static class Test { static void Main() { F(); } static async void F() { await new A(); } public static void GetAwaiter(this object a) { throw new Exception(); } } } public static class EE { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (11,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A")); } [Fact] public void ExtensionParentNamespaceDuellingLookupBad() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } namespace child { public static class Test { static async void F() { await new A(); } static void Main() { F(); } } } public static class E1 { public static void GetAwaiter(this A a) { throw new Exception(); } } public static class E2 { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (23,13): error CS0121: The call is ambiguous between the following methods or properties: 'E1.GetAwaiter(A)' and 'E2.GetAwaiter(A)' // await new A(); Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("E1.GetAwaiter(A)", "E2.GetAwaiter(A)") ); } [Fact] public void ExtensionParentNamespaceDuellingLookupWasGoodNowBad() { var source = @" using System; public class A { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } namespace child { public static class Test { static async void F() { await new A(); } static void Main() { F(); } } } public static class E1 { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } } public static class E2 { public static void GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (23,13): error CS0121: The call is ambiguous between the following methods or properties: 'E1.GetAwaiter(A)' and 'E2.GetAwaiter(A)' // await new A(); Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("E1.GetAwaiter(A)", "E2.GetAwaiter(A)") ); } [Fact] public void ExtensionParentNamespaceSingleClassDuel() { var source = @" using System; public interface I1 { } public interface I2 { } public class A : I1, I2 { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } namespace parent { namespace child { public static class Test { static async void F() { await new A(); } static void Main() { F(); } } } } public static class E2 { public static void GetAwaiter(this I1 a) { throw new Exception(); } public static Awaiter GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact] public void TruncateExtensionMethodLookupAfterFirstNamespace() { var source = @" using System; public interface I1 { } public interface I2 { } public class A : I1, I2 { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } namespace parent { namespace child { public static class Test { public static void Main() { F(); } static async void F() { await new A(); } public static void GetAwaiter(this I1 a) { throw new Exception(); } } public static class E { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } } } } public static class E2 { public static void GetAwaiter(this I1 a) { throw new Exception(); } public static Awaiter GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact] public void BadTruncateExtensionMethodLookupAfterFirstNamespace() { var source = @" using System; public interface I1 { } public interface I2 { } public class A : I1, I2 { } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(System.Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } namespace parent { namespace child { public static class Test { public static void Main() { F(); } static async void F() { await new A(); } public static void GetAwaiter(this I1 a) { throw new Exception(); } } } public static class E { public static Awaiter GetAwaiter(this A a) { throw new Exception(); } } } public static class E2 { public static void GetAwaiter(this I1 a) { throw new Exception(); } public static Awaiter GetAwaiter(this A a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (11,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A")); } [Fact] public void FallbackToGetAwaiterExtensionMethod() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { private Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } static class MyExtensions { public static Awaiter GetAwaiter(this A a) { return new Awaiter(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact] public void BadFallbackToGetAwaiterExtensionMethodInPresenceOfInstanceGetAwaiterMethodWithOptionalParameter() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter(object o = null) { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } static class MyExtensions { public static Awaiter GetAwaiter(this A a) { return new Awaiter(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A")); } [Fact] public void GetAwaiterMethodWithNonZeroArity() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); await new B(); await new C(); await new D(); await new E(); } } class A { public Awaiter GetAwaiter(object o = null) { return null; } } class B { public Awaiter GetAwaiter(object o) { return null; } } class C { } class D { } class E { public Awaiter GetAwaiter() { return null; } public Awaiter GetAwaiter(object o = null) { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } static class MyExtensions { public static Awaiter GetAwaiter(this C a, object o = null) { return new Awaiter(); } public static Awaiter GetAwaiter(this D a, object o) { return new Awaiter(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method // await new A(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A").WithLocation(10, 9), // (11,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'o' of 'B.GetAwaiter(object)' // await new B(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "await new B()").WithArguments("o", "B.GetAwaiter(object)").WithLocation(11, 9), // (12,9): error CS1986: 'await' requires that the type C have a suitable GetAwaiter method // await new C(); Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new C()").WithArguments("C").WithLocation(12, 9), // (13,15): error CS1929: 'D' does not contain a definition for 'GetAwaiter' and the best extension method overload 'MyExtensions.GetAwaiter(C, object)' requires a receiver of type 'C' // await new D(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "new D()").WithArguments("D", "GetAwaiter", "MyExtensions.GetAwaiter(C, object)", "C").WithLocation(13, 15)); } [Fact] public void GetAwaiterMethodWithNonZeroTypeParameterArity() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); await new B(); } } class A { public Awaiter GetAwaiter<T>() { return null; } } class B { } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } static class MyExtensions { public static Awaiter GetAwaiter<T>(this B a) { return null; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'A.GetAwaiter<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly. // await new A(); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "await new A()").WithArguments("A.GetAwaiter<T>()"), // (11,9): error CS0411: The type arguments for method 'MyExtensions.GetAwaiter<T>(B)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // await new B(); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "await new B()").WithArguments("MyExtensions.GetAwaiter<T>(B)") ); } [Fact] public void AwaiterImplementsINotifyCompletion() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); await new B(); await new C(); await new D(); } } class A { public Awaiter1 GetAwaiter() { return null; } } class B { public Awaiter2 GetAwaiter() { return null; } } class C { public Awaiter3 GetAwaiter() { return null; } } class D { public Awaiter4 GetAwaiter() { return null; } } class Awaiter1 : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } class OnCompletedImpl : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } } class Awaiter2 : OnCompletedImpl { public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } interface OnCompletedInterface : System.Runtime.CompilerServices.INotifyCompletion { } class Awaiter3 : OnCompletedInterface { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } class Awaiter4 { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (13,9): error CS4027: 'Awaiter4' does not implement 'System.Runtime.CompilerServices.INotifyCompletion' // await new D(); Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new D()").WithArguments("Awaiter4", "System.Runtime.CompilerServices.INotifyCompletion")); } [WorkItem(770448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770448")] [Fact] public void AwaiterImplementsINotifyCompletion_Constraint() { var source = @"using System.Runtime.CompilerServices; class Awaitable<T> { internal T GetAwaiter() { return default(T); } } interface IA { bool IsCompleted { get; } object GetResult(); } interface IB : IA, INotifyCompletion { } class A { public void OnCompleted(System.Action a) { } internal bool IsCompleted { get { return true; } } internal object GetResult() { return null; } } class B : A, INotifyCompletion { } class C { static async void F<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>() where T1 : IA where T2 : IA, INotifyCompletion where T3 : IB where T4 : T1, INotifyCompletion where T5 : T3 where T6 : A where T7 : A, INotifyCompletion where T8 : B where T9 : T6, INotifyCompletion where T10 : T8 { await new Awaitable<T1>(); await new Awaitable<T2>(); await new Awaitable<T3>(); await new Awaitable<T4>(); await new Awaitable<T5>(); await new Awaitable<T6>(); await new Awaitable<T7>(); await new Awaitable<T8>(); await new Awaitable<T9>(); await new Awaitable<T10>(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (37,9): error CS4027: 'T1' does not implement 'System.Runtime.CompilerServices.INotifyCompletion' // await new Awaitable<T1>(); Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<T1>()").WithArguments("T1", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(37, 9), // (42,9): error CS4027: 'T6' does not implement 'System.Runtime.CompilerServices.INotifyCompletion' // await new Awaitable<T6>(); Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<T6>()").WithArguments("T6", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(42, 9)); } [WorkItem(770448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770448")] [Fact] public void AwaiterImplementsINotifyCompletion_InheritedConstraint() { var source = @"using System; using System.Runtime.CompilerServices; class Awaitable<T> { internal T GetAwaiter() { return default(T); } } interface IA { bool IsCompleted { get; } object GetResult(); } interface IB : IA, INotifyCompletion { } class B : IA, INotifyCompletion { public void OnCompleted(Action a) { } public bool IsCompleted { get { return true; } } public object GetResult() { return null; } } struct S : IA, INotifyCompletion { public void OnCompleted(Action a) { } public bool IsCompleted { get { return true; } } public object GetResult() { return null; } } class C<T> where T : IA { internal virtual async void F<U>() where U : T { await new Awaitable<U>(); } } class D1 : C<IB> { internal override async void F<T1>() { await new Awaitable<T1>(); } } class D2 : C<B> { internal override async void F<T2>() { await new Awaitable<T2>(); } } class D3 : C<S> { internal override async void F<T3>() { await new Awaitable<T3>(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (31,9): error CS4027: 'U' does not implement 'System.Runtime.CompilerServices.INotifyCompletion' // await new Awaitable<U>(); Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<U>()").WithArguments("U", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(31, 9), // (52,9): error CS0117: 'T3' does not contain a definition for 'IsCompleted' // await new Awaitable<T3>(); Diagnostic(ErrorCode.ERR_NoSuchMember, "await new Awaitable<T3>()").WithArguments("T3", "IsCompleted").WithLocation(52, 9)); } [WorkItem(770448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770448")] [Fact] public void AwaiterImplementsINotifyCompletion_UserDefinedConversion() { var source = @"using System; using System.Runtime.CompilerServices; class Awaitable<T> { internal T GetAwaiter() { return default(T); } } interface IA : INotifyCompletion { bool IsCompleted { get; } object GetResult(); } class A : INotifyCompletion { public void OnCompleted(Action a) { } public bool IsCompleted { get { return true; } } public object GetResult() { return null; } } class B { public void OnCompleted(Action a) { } public bool IsCompleted { get { return true; } } public static implicit operator A(B b) { return default(A); } } class B<T> where T : INotifyCompletion { public void OnCompleted(Action a) { } public bool IsCompleted { get { return true; } } public static implicit operator T(B<T> b) { return default(T); } } class C { async void F() { await new Awaitable<B>(); await new Awaitable<B<IA>>(); await new Awaitable<B<A>>(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (34,9): error CS4027: 'B' does not implement 'System.Runtime.CompilerServices.INotifyCompletion' // await new Awaitable<B>(); Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<B>()").WithArguments("B", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(34, 9), // (35,9): error CS4027: 'B<IA>' does not implement 'System.Runtime.CompilerServices.INotifyCompletion' // await new Awaitable<B<IA>>(); Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<B<IA>>()").WithArguments("B<IA>", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(35, 9), // (36,9): error CS4027: 'B<A>' does not implement 'System.Runtime.CompilerServices.INotifyCompletion' // await new Awaitable<B<A>>(); Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<B<A>>()").WithArguments("B<A>", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(36, 9)); } /// <summary> /// Should call ICriticalNotifyCompletion.UnsafeOnCompleted /// if the awaiter type implements ICriticalNotifyCompletion. /// </summary> [Fact] public void AwaiterImplementsICriticalNotifyCompletion_Constraint() { var source = @"using System; using System.Runtime.CompilerServices; class Awaitable<T> { internal T GetAwaiter() { return default(T); } } class A : INotifyCompletion { public void OnCompleted(Action a) { } public bool IsCompleted { get { return true; } } public object GetResult() { return null; } } class B : A, ICriticalNotifyCompletion { public void UnsafeOnCompleted(Action a) { } } class C { static async void F<T1, T2, T3, T4, T5, T6>() where T1 : A where T2 : A, ICriticalNotifyCompletion where T3 : B where T4 : T1 where T5 : T2 where T6 : T1, ICriticalNotifyCompletion { await new Awaitable<T1>(); await new Awaitable<T2>(); await new Awaitable<T3>(); await new Awaitable<T4>(); await new Awaitable<T5>(); await new Awaitable<T6>(); } }"; var compilation = CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); var verifier = CompileAndVerify(compilation); var actualIL = verifier.VisualizeIL("C.<F>d__0<T1, T2, T3, T4, T5, T6>.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()"); var calls = actualIL.Split(new[] { '\n', '\r' }, System.StringSplitOptions.RemoveEmptyEntries).Where(s => s.Contains("OnCompleted")).ToArray(); Assert.Equal(6, calls.Length); Assert.Equal(" IL_0056: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitOnCompleted<T1, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T1, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[0]); Assert.Equal(" IL_00b9: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<T2, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T2, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[1]); Assert.Equal(" IL_011c: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<T3, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T3, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[2]); Assert.Equal(" IL_0182: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitOnCompleted<T4, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T4, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[3]); Assert.Equal(" IL_01ea: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<T5, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T5, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[4]); Assert.Equal(" IL_0252: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<T6, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T6, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[5]); } [Fact] public void ConditionalOnCompletedImplementation() { var source = @" using System; using System.Diagnostics; static class Program { static void Main() { } static async void f() { await new A(); await new B(); } } class A { public Awaiter GetAwaiter() { return null; } } class B { } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { [Conditional(""Condition"")] public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } } static class MyExtensions { public static Awaiter GetAwaiter(this B a) { return null; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (28,17): error CS0629: Conditional member 'Awaiter.OnCompleted(System.Action)' cannot implement interface member 'System.Runtime.CompilerServices.INotifyCompletion.OnCompleted(System.Action)' in type 'Awaiter' // public void OnCompleted(Action x) { } Diagnostic(ErrorCode.ERR_InterfaceImplementedByConditional, "OnCompleted").WithArguments("Awaiter.OnCompleted(System.Action)", "System.Runtime.CompilerServices.INotifyCompletion.OnCompleted(System.Action)", "Awaiter")); } [Fact] public void MissingIsCompletedProperty() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0117: 'Awaiter' does not contain a definition for 'IsCompleted' // await new A(); Diagnostic(ErrorCode.ERR_NoSuchMember, "await new A()").WithArguments("Awaiter", "IsCompleted")); } [Fact] public void InaccessibleIsCompletedProperty() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } bool IsCompleted { get { return false; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0117: 'Awaiter' does not contain a definition for 'IsCompleted' // await new A(); Diagnostic(ErrorCode.ERR_NoSuchMember, "await new A()").WithArguments("Awaiter", "IsCompleted")); } [Fact] public void StaticIsCompletedProperty() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public static bool IsCompleted { get { return false; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0176: Member 'Awaiter.IsCompleted' cannot be accessed with an instance reference; qualify it with a type name instead // await new A(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "await new A()").WithArguments("Awaiter.IsCompleted") ); } [Fact] public void StaticWriteonlyIsCompletedProperty() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public static bool IsCompleted { set { } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0176: Member 'Awaiter.IsCompleted' cannot be accessed with an instance reference; qualify it with a type name instead // await new A(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "await new A()").WithArguments("Awaiter.IsCompleted") ); } [Fact] public void StaticAccessorlessIsCompletedProperty() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public static bool IsCompleted { } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (25,24): error CS0548: 'Awaiter.IsCompleted': property or indexer must have at least one accessor // public static bool IsCompleted { } Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "IsCompleted").WithArguments("Awaiter.IsCompleted"), // (10,9): error CS0176: Member 'Awaiter.IsCompleted' cannot be accessed with an instance reference; qualify it with a type name instead // await new A(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "await new A()").WithArguments("Awaiter.IsCompleted") ); } [Fact] public void NonBooleanIsCompletedProperty() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public int IsCompleted { get { return -1; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS4011: 'await' requires that the return type 'Awaiter' of 'A.GetAwaiter()' have suitable IsCompleted, OnCompleted, and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion // await new A(); Diagnostic(ErrorCode.ERR_BadAwaiterPattern, "await new A()").WithArguments("Awaiter", "A")); } [Fact] public void WriteonlyIsCompletedProperty() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public bool IsCompleted { set { } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0117: 'A' does not contain a definition for 'IsCompleted' // await new A(); Diagnostic(ErrorCode.ERR_PropertyLacksGet, "await new A()").WithArguments("Awaiter.IsCompleted")); } [Fact] public void WriteonlyNonBooleanIsCompletedProperty() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult() { throw new Exception(); } public int IsCompleted { set { } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0117: 'A' does not contain a definition for 'IsCompleted' // await new A(); Diagnostic(ErrorCode.ERR_PropertyLacksGet, "await new A()").WithArguments("Awaiter.IsCompleted")); } [Fact] public void MissingGetResultInstanceMethod() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool IsCompleted { get { return false; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0117: 'Awaiter' does not contain a definition for 'GetResult' // await new A(); Diagnostic(ErrorCode.ERR_NoSuchMember, "await new A()").WithArguments("Awaiter", "GetResult")); } [Fact] public void InaccessibleGetResultInstanceMethod() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } private bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return false; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0122: 'Awaiter.GetResult()' is inaccessible due to its protection level // await new A(); Diagnostic(ErrorCode.ERR_BadAccess, "await new A()").WithArguments("Awaiter.GetResult()") ); } [Fact] public void StaticResultMethod() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public static bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return false; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0176: Member 'Awaiter.GetResult()' cannot be accessed with an instance reference; qualify it with a type name instead // await new A(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "await new A()").WithArguments("Awaiter.GetResult()")); } [Fact] public void GetResultExtensionMethod() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool IsCompleted { get { return false; } } } static class MyExtensions { public static bool GetResult(this Awaiter a) { throw new Exception(); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0117: 'Awaiter' does not contain a definition for 'GetResult' // await new A(); Diagnostic(ErrorCode.ERR_NoSuchMember, "await new A()").WithArguments("Awaiter", "GetResult")); } [Fact] public void GetResultWithNonZeroArity() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult(object o = null) { throw new Exception(); } public bool IsCompleted { get { return false; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS4011: 'await' requires that the return type 'Awaiter' of 'A.GetAwaiter()' have suitable IsCompleted, OnCompleted, and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion // await new A(); Diagnostic(ErrorCode.ERR_BadAwaiterPattern, "await new A()").WithArguments("Awaiter", "A")); } [Fact] public void GetResultWithNonZeroTypeParameterArity() { var source = @" using System; static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public bool GetResult<T>() { throw new Exception(); } public bool IsCompleted { get { return false; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'Awaiter.GetResult<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly. // await new A(); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "await new A()").WithArguments("Awaiter.GetResult<T>()") ); } [Fact] public void ConditionalGetResult() { var source = @" using System; using System.Diagnostics; static class Program { static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return new Awaiter(); } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } [Conditional(""X"")] public void GetResult() { Console.WriteLine(""unconditional""); } public bool IsCompleted { get { return true; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (15,9): error CS4011: 'await' requires that the return type 'Awaiter' of 'A.GetAwaiter()' have suitable IsCompleted, OnCompleted, and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion // await new A(); Diagnostic(ErrorCode.ERR_BadAwaiterPattern, "await new A()").WithArguments("Awaiter", "A")); } [Fact] public void Missing_IsCompleted_INotifyCompletion_GetResult() { var source = @" static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter //: System.Runtime.CompilerServices.INotifyCompletion { //public void OnCompleted(Action x) { } //public bool GetResult() { throw new Exception(); } //public bool IsCompleted { get { return true; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (8,9): error CS0117: 'Awaiter' does not contain a definition for 'IsCompleted' // await new A(); Diagnostic(ErrorCode.ERR_NoSuchMember, "await new A()").WithArguments("Awaiter", "IsCompleted")); } [Fact] public void Missing_INotifyCompletion_GetResult() { var source = @" static class Program { static void Main() { } static async void f() { await new A(); } } class A { public Awaiter GetAwaiter() { return null; } } class Awaiter //: System.Runtime.CompilerServices.INotifyCompletion { //public void OnCompleted(Action x) { } //public bool GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (8,9): error CS4027: 'Awaiter' does not implement 'System.Runtime.CompilerServices.INotifyCompletion' // await new A(); Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new A()").WithArguments("Awaiter", "System.Runtime.CompilerServices.INotifyCompletion")); } [Fact] public void BadAwaitArg_NeedSystem() { var source = @" // using System; using System.Threading.Tasks; using Windows.Devices.Enumeration; class App { static void Main() { EnumDevices().Wait(); } private static async Task EnumDevices() { await DeviceInformation.FindAllAsync(); return; } }"; CreateCompilationWithWinRT(source).VerifyDiagnostics( // (12,9): error CS4035: 'Windows.Foundation.IAsyncOperation<Windows.Devices.Enumeration.DeviceInformationCollection>' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'Windows.Foundation.IAsyncOperation<Windows.Devices.Enumeration.DeviceInformationCollection>' could be found (are you missing a using directive for 'System'?) // await DeviceInformation.FindAllAsync(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtensionNeedUsing, "await DeviceInformation.FindAllAsync()").WithArguments("Windows.Foundation.IAsyncOperation<Windows.Devices.Enumeration.DeviceInformationCollection>", "GetAwaiter", "System") ); } [Fact] public void ErrorInAwaitSubexpression() { var source = @" class C { async void M() { using (await goo()) { } } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,22): error CS0103: The name 'goo' does not exist in the current context // using (await goo()) Diagnostic(ErrorCode.ERR_NameNotInContext, "goo").WithArguments("goo")); } [Fact] public void BadAwaitArgIntrinsic() { var source = @" class Test { public void goo() { } public async void awaitVoid() { await goo(); } public async void awaitNull() { await null; } public async void awaitMethodGroup() { await goo; } public async void awaitLambda() { await (x => x); } public static void Main() { } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (8,9): error CS4008: Cannot await 'void' // await goo(); Diagnostic(ErrorCode.ERR_BadAwaitArgVoidCall, "await goo()"), // (13,9): error CS4001: Cannot await '<null>;' // await null; Diagnostic(ErrorCode.ERR_BadAwaitArgIntrinsic, "await null").WithArguments("<null>"), // (18,9): error CS4001: Cannot await 'method group' // await goo; Diagnostic(ErrorCode.ERR_BadAwaitArgIntrinsic, "await goo").WithArguments("method group"), // (23,9): error CS4001: Cannot await 'lambda expression' // await (x => x); Diagnostic(ErrorCode.ERR_BadAwaitArgIntrinsic, "await (x => x)").WithArguments("lambda expression")); } [Fact] public void BadAwaitArgVoidCall() { var source = @" using System.Threading.Tasks; class Test { public async void goo() { await Task.Factory.StartNew(() => { }); } public async void bar() { await goo(); } public static void Main() { } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (10,9): error CS4008: Cannot await 'void' // await goo(); Diagnostic(ErrorCode.ERR_BadAwaitArgVoidCall, "await goo()")); } [Fact, WorkItem(531356, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531356")] public void Repro_17997() { var source = @" class C { public IVsTask ResolveReferenceAsync() { return this.VsTasksService.InvokeAsync(async delegate { return null; }); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (4,12): error CS0246: The type or namespace name 'IVsTask' could not be found (are you missing a using directive or an assembly reference?) // public IVsTask ResolveReferenceAsync() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IVsTask").WithArguments("IVsTask").WithLocation(4, 12), // (6,21): error CS1061: 'C' does not contain a definition for 'VsTasksService' and no extension method 'VsTasksService' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // return this.VsTasksService.InvokeAsync(async delegate Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "VsTasksService").WithArguments("C", "VsTasksService").WithLocation(6, 21), // (6,54): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // return this.VsTasksService.InvokeAsync(async delegate Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "delegate").WithLocation(6, 54)); } [Fact, WorkItem(627123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627123")] public void Repro_627123() { var source = @" using System; using System.Runtime.CompilerServices; interface IA : INotifyCompletion { bool IsCompleted { get; } void GetResult(); } interface IB : IA { new Action GetResult { get; } } interface IC { IB GetAwaiter(); } class D { Action<IC> a = async x => await x; }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (23,31): error CS0118: 'GetResult' is a property but is used like a method // Action<IC> a = async x => await x; Diagnostic(ErrorCode.ERR_BadSKknown, "await x").WithArguments("GetResult", "property", "method") ); } [Fact, WorkItem(1091911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091911")] public void Repro_1091911() { const string source = @" using System; using System.Threading.Tasks; class Repro { int Boom { get { return 42; } } static Task<dynamic> Compute() { return Task.FromResult<dynamic>(new Repro()); } static async Task<int> Bug() { dynamic results = await Compute().ConfigureAwait(false); var x = results.Boom; return (int)x; } static void Main() { Console.WriteLine(Bug().Result); } }"; var comp = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [Fact] public void DynamicResultTypeCustomAwaiter() { const string source = @" using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; public struct MyTask { public readonly Task task; private readonly Func<dynamic> getResult; public MyTask(Task task, Func<dynamic> getResult) { this.task = task; this.getResult = getResult; } public dynamic Result { get { return this.getResult(); } } } public struct MyAwaiter : INotifyCompletion { private readonly MyTask task; public MyAwaiter(MyTask task) { this.task = task; } public bool IsCompleted { get { return true; } } public dynamic GetResult() { Console.Write(""dynamic""); return task.Result; } public void OnCompleted(System.Action continuation) { task.task.ContinueWith(_ => continuation()); } } public static class TaskAwaiter { public static MyAwaiter GetAwaiter(this MyTask task) { return new MyAwaiter(task); } } class Repro { int Boom { get { return 42; } } static MyTask Compute() { var task = Task.FromResult(new Repro()); return new MyTask(task, () => task.Result); } static async Task<int> Bug() { return (await Compute()).Boom; } static void Main() { Console.WriteLine(Bug().Result); } } "; var comp = CreateCompilationWithMscorlib45(source, new[] { TestMetadata.Net40.SystemCore, TestMetadata.Net40.MicrosoftCSharp }, TestOptions.ReleaseExe); comp.VerifyDiagnostics( // warning CS1685: The predefined type 'ExtensionAttribute' is defined in multiple assemblies in the global alias; using definition from 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Diagnostic(ErrorCode.WRN_MultiplePredefTypes).WithArguments("System.Runtime.CompilerServices.ExtensionAttribute", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").WithLocation(1, 1)); var compiled = CompileAndVerify(comp, expectedOutput: "dynamic42", verify: Verification.Fails); compiled.VerifyIL("MyAwaiter.OnCompleted(System.Action)", @" { // Code size 43 (0x2b) .maxstack 3 .locals init (MyAwaiter.<>c__DisplayClass5_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""MyAwaiter.<>c__DisplayClass5_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.1 IL_0008: stfld ""System.Action MyAwaiter.<>c__DisplayClass5_0.continuation"" IL_000d: ldarg.0 IL_000e: ldflda ""MyTask MyAwaiter.task"" IL_0013: ldfld ""System.Threading.Tasks.Task MyTask.task"" IL_0018: ldloc.0 IL_0019: ldftn ""void MyAwaiter.<>c__DisplayClass5_0.<OnCompleted>b__0(System.Threading.Tasks.Task)"" IL_001f: newobj ""System.Action<System.Threading.Tasks.Task>..ctor(object, System.IntPtr)"" IL_0024: callvirt ""System.Threading.Tasks.Task System.Threading.Tasks.Task.ContinueWith(System.Action<System.Threading.Tasks.Task>)"" IL_0029: pop IL_002a: ret }"); } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/EditorFeatures/Test/Completion/FileSystemCompletionHelperTests.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.Linq; using System.Threading; using Microsoft.CodeAnalysis.Completion; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Completion { public class FileSystemCompletionHelperTests { private static void AssertItemsEqual(ImmutableArray<CompletionItem> actual, params string[] expected) { AssertEx.Equal( expected, actual.Select(c => $"'{c.DisplayText}', {string.Join(", ", c.Tags)}, '{c.Properties["Description"]}'"), itemInspector: c => $"@\"{c}\""); Assert.True(actual.All(i => i.Rules == TestFileSystemCompletionHelper.CompletionRules)); } [ConditionalFact(typeof(WindowsOnly))] public void GetItems_Windows1() { var fsc = new TestFileSystemCompletionHelper( searchPaths: ImmutableArray.Create(@"X:\A", @"X:\B"), baseDirectoryOpt: @"Z:\C", allowableExtensions: ImmutableArray.Create(".abc", ".def"), drives: new[] { @"X:\", @"Z:\" }, directories: new[] { @"X:", @"X:\A", @"X:\A\1", @"X:\A\2", @"X:\A\3", @"X:\B", @"Z:", @"Z:\C", @"Z:\D", }, files: new[] { @"X:\A\1\file1.abc", @"X:\A\2\file2.abc", @"X:\B\file4.x", @"X:\B\file5.abc", @"X:\B\hidden.def", @"Z:\C\file6.def", @"Z:\C\file.7.def", }); // Note backslashes in description are escaped AssertItemsEqual(fsc.GetTestAccessor().GetItems("", CancellationToken.None), @"'file6.def', File, C#, 'Text|Z:\5CC\5Cfile6.def'", @"'file.7.def', File, C#, 'Text|Z:\5CC\5Cfile.7.def'", @"'X:', Folder, 'Text|X:'", @"'Z:', Folder, 'Text|Z:'", @"'\\', , 'Text|\5C\5C'", @"'1', Folder, 'Text|X:\5CA\5C1'", @"'2', Folder, 'Text|X:\5CA\5C2'", @"'3', Folder, 'Text|X:\5CA\5C3'", @"'file5.abc', File, C#, 'Text|X:\5CB\5Cfile5.abc'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"X:\A\", CancellationToken.None), @"'1', Folder, 'Text|X:\5CA\5C1'", @"'2', Folder, 'Text|X:\5CA\5C2'", @"'3', Folder, 'Text|X:\5CA\5C3'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"X:\B\", CancellationToken.None), @"'file5.abc', File, C#, 'Text|X:\5CB\5Cfile5.abc'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"Z:\", CancellationToken.None), @"'C', Folder, 'Text|Z:\5CC'", @"'D', Folder, 'Text|Z:\5CD'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"Z:", CancellationToken.None), @"'Z:', Folder, 'Text|Z:'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"\", CancellationToken.None), @"'\\', , 'Text|\5C\5C'"); } [ConditionalFact(typeof(WindowsOnly))] public void GetItems_Windows_NoBaseDirectory() { var fsc = new TestFileSystemCompletionHelper( searchPaths: ImmutableArray.Create(@"X:\A", @"X:\B"), baseDirectoryOpt: null, allowableExtensions: ImmutableArray.Create(".abc", ".def"), drives: new[] { @"X:\" }, directories: new[] { @"X:", @"X:\A", @"X:\A\1", @"X:\A\2", @"X:\A\3", @"X:\B", }, files: new[] { @"X:\A\1\file1.abc", @"X:\A\2\file2.abc", @"X:\B\file4.x", @"X:\B\file5.abc", @"X:\B\hidden.def", }); // Note backslashes in description are escaped AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"", CancellationToken.None), @"'X:', Folder, 'Text|X:'", @"'\\', , 'Text|\5C\5C'", @"'1', Folder, 'Text|X:\5CA\5C1'", @"'2', Folder, 'Text|X:\5CA\5C2'", @"'3', Folder, 'Text|X:\5CA\5C3'", @"'file5.abc', File, C#, 'Text|X:\5CB\5Cfile5.abc'"); } [ConditionalFact(typeof(WindowsOnly))] public void GetItems_Windows_NoSearchPaths() { var fsc = new TestFileSystemCompletionHelper( searchPaths: ImmutableArray<string>.Empty, baseDirectoryOpt: null, allowableExtensions: ImmutableArray.Create(".abc", ".def"), drives: new[] { @"X:\" }, directories: new[] { @"X:", @"X:\A", @"X:\A\1", @"X:\A\2", @"X:\A\3", @"X:\B", }, files: new[] { @"X:\A\1\file1.abc", @"X:\A\2\file2.abc", @"X:\B\file4.x", @"X:\B\file5.abc", @"X:\B\hidden.def", }); // Note backslashes in description are escaped AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"", CancellationToken.None), @"'X:', Folder, 'Text|X:'", @"'\\', , 'Text|\5C\5C'"); } [ConditionalFact(typeof(WindowsOnly))] public void GetItems_Windows_Network() { var fsc = new TestFileSystemCompletionHelper( searchPaths: ImmutableArray<string>.Empty, baseDirectoryOpt: null, allowableExtensions: ImmutableArray.Create(".cs"), drives: Array.Empty<string>(), directories: new[] { @"\\server\share", @"\\server\share\C", @"\\server\share\D", }, files: new[] { @"\\server\share\C\b.cs", @"\\server\share\C\c.cs", @"\\server\share\D\e.cs", }); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"\\server\share\", CancellationToken.None), @"'C', Folder, 'Text|\5C\5Cserver\5Cshare\5CC'", @"'D', Folder, 'Text|\5C\5Cserver\5Cshare\5CD'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"\\server\share\C\", CancellationToken.None), @"'b.cs', File, C#, 'Text|\5C\5Cserver\5Cshare\5CC\5Cb.cs'", @"'c.cs', File, C#, 'Text|\5C\5Cserver\5Cshare\5CC\5Cc.cs'"); } [ConditionalFact(typeof(UnixLikeOnly))] public void GetItems_Unix1() { var fsc = new TestFileSystemCompletionHelper( searchPaths: ImmutableArray.Create(@"/A", @"/B"), baseDirectoryOpt: @"/C", allowableExtensions: ImmutableArray.Create(".abc", ".def"), drives: Array.Empty<string>(), directories: new[] { @"/A", @"/A/1", @"/A/2", @"/A/3", @"/B", @"/C", @"/D", }, files: new[] { @"/A/1/file1.abc", @"/A/2/file2.abc", @"/B/file4.x", @"/B/file5.abc", @"/B/hidden.def", @"/C/file6.def", @"/C/file.7.def", }); // Note backslashes in description are escaped AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"", CancellationToken.None), @"'file6.def', File, C#, 'Text|/C/file6.def'", @"'file.7.def', File, C#, 'Text|/C/file.7.def'", @"'/', Folder, 'Text|/'", @"'1', Folder, 'Text|/A/1'", @"'2', Folder, 'Text|/A/2'", @"'3', Folder, 'Text|/A/3'", @"'file5.abc', File, C#, 'Text|/B/file5.abc'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"/", CancellationToken.None), @"'A', Folder, 'Text|/A'", @"'B', Folder, 'Text|/B'", @"'C', Folder, 'Text|/C'", @"'D', Folder, 'Text|/D'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"/B/", CancellationToken.None), @"'file5.abc', File, C#, 'Text|/B/file5.abc'"); } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading; using Microsoft.CodeAnalysis.Completion; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Completion { public class FileSystemCompletionHelperTests { private static void AssertItemsEqual(ImmutableArray<CompletionItem> actual, params string[] expected) { AssertEx.Equal( expected, actual.Select(c => $"'{c.DisplayText}', {string.Join(", ", c.Tags)}, '{c.Properties["Description"]}'"), itemInspector: c => $"@\"{c}\""); Assert.True(actual.All(i => i.Rules == TestFileSystemCompletionHelper.CompletionRules)); } [ConditionalFact(typeof(WindowsOnly))] public void GetItems_Windows1() { var fsc = new TestFileSystemCompletionHelper( searchPaths: ImmutableArray.Create(@"X:\A", @"X:\B"), baseDirectoryOpt: @"Z:\C", allowableExtensions: ImmutableArray.Create(".abc", ".def"), drives: new[] { @"X:\", @"Z:\" }, directories: new[] { @"X:", @"X:\A", @"X:\A\1", @"X:\A\2", @"X:\A\3", @"X:\B", @"Z:", @"Z:\C", @"Z:\D", }, files: new[] { @"X:\A\1\file1.abc", @"X:\A\2\file2.abc", @"X:\B\file4.x", @"X:\B\file5.abc", @"X:\B\hidden.def", @"Z:\C\file6.def", @"Z:\C\file.7.def", }); // Note backslashes in description are escaped AssertItemsEqual(fsc.GetTestAccessor().GetItems("", CancellationToken.None), @"'file6.def', File, C#, 'Text|Z:\5CC\5Cfile6.def'", @"'file.7.def', File, C#, 'Text|Z:\5CC\5Cfile.7.def'", @"'X:', Folder, 'Text|X:'", @"'Z:', Folder, 'Text|Z:'", @"'\\', , 'Text|\5C\5C'", @"'1', Folder, 'Text|X:\5CA\5C1'", @"'2', Folder, 'Text|X:\5CA\5C2'", @"'3', Folder, 'Text|X:\5CA\5C3'", @"'file5.abc', File, C#, 'Text|X:\5CB\5Cfile5.abc'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"X:\A\", CancellationToken.None), @"'1', Folder, 'Text|X:\5CA\5C1'", @"'2', Folder, 'Text|X:\5CA\5C2'", @"'3', Folder, 'Text|X:\5CA\5C3'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"X:\B\", CancellationToken.None), @"'file5.abc', File, C#, 'Text|X:\5CB\5Cfile5.abc'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"Z:\", CancellationToken.None), @"'C', Folder, 'Text|Z:\5CC'", @"'D', Folder, 'Text|Z:\5CD'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"Z:", CancellationToken.None), @"'Z:', Folder, 'Text|Z:'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"\", CancellationToken.None), @"'\\', , 'Text|\5C\5C'"); } [ConditionalFact(typeof(WindowsOnly))] public void GetItems_Windows_NoBaseDirectory() { var fsc = new TestFileSystemCompletionHelper( searchPaths: ImmutableArray.Create(@"X:\A", @"X:\B"), baseDirectoryOpt: null, allowableExtensions: ImmutableArray.Create(".abc", ".def"), drives: new[] { @"X:\" }, directories: new[] { @"X:", @"X:\A", @"X:\A\1", @"X:\A\2", @"X:\A\3", @"X:\B", }, files: new[] { @"X:\A\1\file1.abc", @"X:\A\2\file2.abc", @"X:\B\file4.x", @"X:\B\file5.abc", @"X:\B\hidden.def", }); // Note backslashes in description are escaped AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"", CancellationToken.None), @"'X:', Folder, 'Text|X:'", @"'\\', , 'Text|\5C\5C'", @"'1', Folder, 'Text|X:\5CA\5C1'", @"'2', Folder, 'Text|X:\5CA\5C2'", @"'3', Folder, 'Text|X:\5CA\5C3'", @"'file5.abc', File, C#, 'Text|X:\5CB\5Cfile5.abc'"); } [ConditionalFact(typeof(WindowsOnly))] public void GetItems_Windows_NoSearchPaths() { var fsc = new TestFileSystemCompletionHelper( searchPaths: ImmutableArray<string>.Empty, baseDirectoryOpt: null, allowableExtensions: ImmutableArray.Create(".abc", ".def"), drives: new[] { @"X:\" }, directories: new[] { @"X:", @"X:\A", @"X:\A\1", @"X:\A\2", @"X:\A\3", @"X:\B", }, files: new[] { @"X:\A\1\file1.abc", @"X:\A\2\file2.abc", @"X:\B\file4.x", @"X:\B\file5.abc", @"X:\B\hidden.def", }); // Note backslashes in description are escaped AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"", CancellationToken.None), @"'X:', Folder, 'Text|X:'", @"'\\', , 'Text|\5C\5C'"); } [ConditionalFact(typeof(WindowsOnly))] public void GetItems_Windows_Network() { var fsc = new TestFileSystemCompletionHelper( searchPaths: ImmutableArray<string>.Empty, baseDirectoryOpt: null, allowableExtensions: ImmutableArray.Create(".cs"), drives: Array.Empty<string>(), directories: new[] { @"\\server\share", @"\\server\share\C", @"\\server\share\D", }, files: new[] { @"\\server\share\C\b.cs", @"\\server\share\C\c.cs", @"\\server\share\D\e.cs", }); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"\\server\share\", CancellationToken.None), @"'C', Folder, 'Text|\5C\5Cserver\5Cshare\5CC'", @"'D', Folder, 'Text|\5C\5Cserver\5Cshare\5CD'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"\\server\share\C\", CancellationToken.None), @"'b.cs', File, C#, 'Text|\5C\5Cserver\5Cshare\5CC\5Cb.cs'", @"'c.cs', File, C#, 'Text|\5C\5Cserver\5Cshare\5CC\5Cc.cs'"); } [ConditionalFact(typeof(UnixLikeOnly))] public void GetItems_Unix1() { var fsc = new TestFileSystemCompletionHelper( searchPaths: ImmutableArray.Create(@"/A", @"/B"), baseDirectoryOpt: @"/C", allowableExtensions: ImmutableArray.Create(".abc", ".def"), drives: Array.Empty<string>(), directories: new[] { @"/A", @"/A/1", @"/A/2", @"/A/3", @"/B", @"/C", @"/D", }, files: new[] { @"/A/1/file1.abc", @"/A/2/file2.abc", @"/B/file4.x", @"/B/file5.abc", @"/B/hidden.def", @"/C/file6.def", @"/C/file.7.def", }); // Note backslashes in description are escaped AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"", CancellationToken.None), @"'file6.def', File, C#, 'Text|/C/file6.def'", @"'file.7.def', File, C#, 'Text|/C/file.7.def'", @"'/', Folder, 'Text|/'", @"'1', Folder, 'Text|/A/1'", @"'2', Folder, 'Text|/A/2'", @"'3', Folder, 'Text|/A/3'", @"'file5.abc', File, C#, 'Text|/B/file5.abc'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"/", CancellationToken.None), @"'A', Folder, 'Text|/A'", @"'B', Folder, 'Text|/B'", @"'C', Folder, 'Text|/C'", @"'D', Folder, 'Text|/D'"); AssertItemsEqual(fsc.GetTestAccessor().GetItems(@"/B/", CancellationToken.None), @"'file5.abc', File, C#, 'Text|/B/file5.abc'"); } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Features/Core/Portable/ImplementInterface/AbstractImplementInterfaceService.CodeAction_Property.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ImplementType; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ImplementInterface { internal abstract partial class AbstractImplementInterfaceService { internal partial class ImplementInterfaceCodeAction { private ISymbol GenerateProperty( Compilation compilation, IPropertySymbol property, Accessibility accessibility, DeclarationModifiers modifiers, bool generateAbstractly, bool useExplicitInterfaceSymbol, string memberName, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior) { var factory = Document.GetLanguageService<SyntaxGenerator>(); var attributesToRemove = AttributesToRemove(compilation); var getAccessor = GenerateGetAccessor( compilation, property, accessibility, generateAbstractly, useExplicitInterfaceSymbol, propertyGenerationBehavior, attributesToRemove); var setAccessor = GenerateSetAccessor( compilation, property, accessibility, generateAbstractly, useExplicitInterfaceSymbol, propertyGenerationBehavior, attributesToRemove); var syntaxFacts = Document.Project.LanguageServices.GetRequiredService<ISyntaxFactsService>(); var parameterNames = NameGenerator.EnsureUniqueness( property.Parameters.SelectAsArray(p => p.Name), isCaseSensitive: syntaxFacts.IsCaseSensitive); var updatedProperty = property.RenameParameters(parameterNames); updatedProperty = updatedProperty.RemoveInaccessibleAttributesAndAttributesOfTypes(compilation.Assembly, attributesToRemove); return CodeGenerationSymbolFactory.CreatePropertySymbol( updatedProperty, accessibility: accessibility, modifiers: modifiers, explicitInterfaceImplementations: useExplicitInterfaceSymbol ? ImmutableArray.Create(property) : default, name: memberName, getMethod: getAccessor, setMethod: setAccessor); } /// <summary> /// Lists compiler attributes that we want to remove. /// The TupleElementNames attribute is compiler generated (it is used for naming tuple element names). /// We never want to place it in source code. /// Same thing for the Dynamic attribute. /// </summary> private static INamedTypeSymbol[] AttributesToRemove(Compilation compilation) { return new[] { compilation.ComAliasNameAttributeType(), compilation.TupleElementNamesAttributeType(), compilation.DynamicAttributeType(), compilation.NativeIntegerAttributeType() }.WhereNotNull().ToArray()!; } private IMethodSymbol? GenerateSetAccessor( Compilation compilation, IPropertySymbol property, Accessibility accessibility, bool generateAbstractly, bool useExplicitInterfaceSymbol, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior, INamedTypeSymbol[] attributesToRemove) { if (property.SetMethod == null) { return null; } if (property.GetMethod == null) { // Can't have an auto-prop with just a setter. propertyGenerationBehavior = ImplementTypePropertyGenerationBehavior.PreferThrowingProperties; } var setMethod = property.SetMethod.RemoveInaccessibleAttributesAndAttributesOfTypes( State.ClassOrStructType, attributesToRemove); return CodeGenerationSymbolFactory.CreateAccessorSymbol( setMethod, attributes: default, accessibility: accessibility, explicitInterfaceImplementations: useExplicitInterfaceSymbol ? ImmutableArray.Create(property.SetMethod) : default, statements: GetSetAccessorStatements( compilation, property, generateAbstractly, propertyGenerationBehavior)); } private IMethodSymbol? GenerateGetAccessor( Compilation compilation, IPropertySymbol property, Accessibility accessibility, bool generateAbstractly, bool useExplicitInterfaceSymbol, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior, INamedTypeSymbol[] attributesToRemove) { if (property.GetMethod == null) { return null; } var getMethod = property.GetMethod.RemoveInaccessibleAttributesAndAttributesOfTypes( State.ClassOrStructType, attributesToRemove); return CodeGenerationSymbolFactory.CreateAccessorSymbol( getMethod, attributes: default, accessibility: accessibility, explicitInterfaceImplementations: useExplicitInterfaceSymbol ? ImmutableArray.Create(property.GetMethod) : default, statements: GetGetAccessorStatements( compilation, property, generateAbstractly, propertyGenerationBehavior)); } private ImmutableArray<SyntaxNode> GetSetAccessorStatements( Compilation compilation, IPropertySymbol property, bool generateAbstractly, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior) { if (generateAbstractly) return default; var generator = Document.GetRequiredLanguageService<SyntaxGenerator>(); return generator.GetSetAccessorStatements(compilation, property, ThroughMember, propertyGenerationBehavior == ImplementTypePropertyGenerationBehavior.PreferAutoProperties); } private ImmutableArray<SyntaxNode> GetGetAccessorStatements( Compilation compilation, IPropertySymbol property, bool generateAbstractly, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior) { if (generateAbstractly) return default; var generator = Document.Project.LanguageServices.GetRequiredService<SyntaxGenerator>(); return generator.GetGetAccessorStatements(compilation, property, ThroughMember, propertyGenerationBehavior == ImplementTypePropertyGenerationBehavior.PreferAutoProperties); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ImplementType; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ImplementInterface { internal abstract partial class AbstractImplementInterfaceService { internal partial class ImplementInterfaceCodeAction { private ISymbol GenerateProperty( Compilation compilation, IPropertySymbol property, Accessibility accessibility, DeclarationModifiers modifiers, bool generateAbstractly, bool useExplicitInterfaceSymbol, string memberName, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior) { var factory = Document.GetLanguageService<SyntaxGenerator>(); var attributesToRemove = AttributesToRemove(compilation); var getAccessor = GenerateGetAccessor( compilation, property, accessibility, generateAbstractly, useExplicitInterfaceSymbol, propertyGenerationBehavior, attributesToRemove); var setAccessor = GenerateSetAccessor( compilation, property, accessibility, generateAbstractly, useExplicitInterfaceSymbol, propertyGenerationBehavior, attributesToRemove); var syntaxFacts = Document.Project.LanguageServices.GetRequiredService<ISyntaxFactsService>(); var parameterNames = NameGenerator.EnsureUniqueness( property.Parameters.SelectAsArray(p => p.Name), isCaseSensitive: syntaxFacts.IsCaseSensitive); var updatedProperty = property.RenameParameters(parameterNames); updatedProperty = updatedProperty.RemoveInaccessibleAttributesAndAttributesOfTypes(compilation.Assembly, attributesToRemove); return CodeGenerationSymbolFactory.CreatePropertySymbol( updatedProperty, accessibility: accessibility, modifiers: modifiers, explicitInterfaceImplementations: useExplicitInterfaceSymbol ? ImmutableArray.Create(property) : default, name: memberName, getMethod: getAccessor, setMethod: setAccessor); } /// <summary> /// Lists compiler attributes that we want to remove. /// The TupleElementNames attribute is compiler generated (it is used for naming tuple element names). /// We never want to place it in source code. /// Same thing for the Dynamic attribute. /// </summary> private static INamedTypeSymbol[] AttributesToRemove(Compilation compilation) { return new[] { compilation.ComAliasNameAttributeType(), compilation.TupleElementNamesAttributeType(), compilation.DynamicAttributeType(), compilation.NativeIntegerAttributeType() }.WhereNotNull().ToArray()!; } private IMethodSymbol? GenerateSetAccessor( Compilation compilation, IPropertySymbol property, Accessibility accessibility, bool generateAbstractly, bool useExplicitInterfaceSymbol, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior, INamedTypeSymbol[] attributesToRemove) { if (property.SetMethod == null) { return null; } if (property.GetMethod == null) { // Can't have an auto-prop with just a setter. propertyGenerationBehavior = ImplementTypePropertyGenerationBehavior.PreferThrowingProperties; } var setMethod = property.SetMethod.RemoveInaccessibleAttributesAndAttributesOfTypes( State.ClassOrStructType, attributesToRemove); return CodeGenerationSymbolFactory.CreateAccessorSymbol( setMethod, attributes: default, accessibility: accessibility, explicitInterfaceImplementations: useExplicitInterfaceSymbol ? ImmutableArray.Create(property.SetMethod) : default, statements: GetSetAccessorStatements( compilation, property, generateAbstractly, propertyGenerationBehavior)); } private IMethodSymbol? GenerateGetAccessor( Compilation compilation, IPropertySymbol property, Accessibility accessibility, bool generateAbstractly, bool useExplicitInterfaceSymbol, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior, INamedTypeSymbol[] attributesToRemove) { if (property.GetMethod == null) { return null; } var getMethod = property.GetMethod.RemoveInaccessibleAttributesAndAttributesOfTypes( State.ClassOrStructType, attributesToRemove); return CodeGenerationSymbolFactory.CreateAccessorSymbol( getMethod, attributes: default, accessibility: accessibility, explicitInterfaceImplementations: useExplicitInterfaceSymbol ? ImmutableArray.Create(property.GetMethod) : default, statements: GetGetAccessorStatements( compilation, property, generateAbstractly, propertyGenerationBehavior)); } private ImmutableArray<SyntaxNode> GetSetAccessorStatements( Compilation compilation, IPropertySymbol property, bool generateAbstractly, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior) { if (generateAbstractly) return default; var generator = Document.GetRequiredLanguageService<SyntaxGenerator>(); return generator.GetSetAccessorStatements(compilation, property, ThroughMember, propertyGenerationBehavior == ImplementTypePropertyGenerationBehavior.PreferAutoProperties); } private ImmutableArray<SyntaxNode> GetGetAccessorStatements( Compilation compilation, IPropertySymbol property, bool generateAbstractly, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior) { if (generateAbstractly) return default; var generator = Document.Project.LanguageServices.GetRequiredService<SyntaxGenerator>(); return generator.GetGetAccessorStatements(compilation, property, ThroughMember, propertyGenerationBehavior == ImplementTypePropertyGenerationBehavior.PreferAutoProperties); } } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Features/LanguageServer/Protocol/Handler/DocumentChanges/DidCloseHandler.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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.DocumentChanges { [ExportLspRequestHandlerProvider, Shared] [ProvidesMethod(LSP.Methods.TextDocumentDidCloseName)] internal class DidCloseHandler : AbstractStatelessRequestHandler<LSP.DidCloseTextDocumentParams, object?> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DidCloseHandler() { } public override string Method => LSP.Methods.TextDocumentDidCloseName; public override bool MutatesSolutionState => true; public override bool RequiresLSPSolution => false; public override LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.DidCloseTextDocumentParams request) => request.TextDocument; public override Task<object?> HandleRequestAsync(LSP.DidCloseTextDocumentParams request, RequestContext context, CancellationToken cancellationToken) { // GetTextDocumentIdentifier returns null to avoid creating the solution, so the queue is not able to log the uri. context.TraceInformation($"didClose for {request.TextDocument.Uri}"); context.StopTracking(request.TextDocument.Uri); return SpecializedTasks.Default<object>(); } } }
// Licensed to the .NET Foundation under one or more 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.DocumentChanges { [ExportLspRequestHandlerProvider, Shared] [ProvidesMethod(LSP.Methods.TextDocumentDidCloseName)] internal class DidCloseHandler : AbstractStatelessRequestHandler<LSP.DidCloseTextDocumentParams, object?> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DidCloseHandler() { } public override string Method => LSP.Methods.TextDocumentDidCloseName; public override bool MutatesSolutionState => true; public override bool RequiresLSPSolution => false; public override LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.DidCloseTextDocumentParams request) => request.TextDocument; public override Task<object?> HandleRequestAsync(LSP.DidCloseTextDocumentParams request, RequestContext context, CancellationToken cancellationToken) { // GetTextDocumentIdentifier returns null to avoid creating the solution, so the queue is not able to log the uri. context.TraceInformation($"didClose for {request.TextDocument.Uri}"); context.StopTracking(request.TextDocument.Uri); return SpecializedTasks.Default<object>(); } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Compilers/Test/Resources/Core/SymbolsTests/NoPia/ParametersWithoutNames.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.Reflection; using System.Reflection.Emit; using System.Runtime.InteropServices; class Program { /// <summary> /// Compile and run this program to generate ParametersWithoutNames.dll /// </summary> static void Main() { var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("ParametersWithoutNames"), AssemblyBuilderAccess.Save, new[] { new CustomAttributeBuilder(typeof(ImportedFromTypeLibAttribute).GetConstructor(new[] { typeof(string) }), new[] { "GeneralPIA.dll" }), new CustomAttributeBuilder(typeof(GuidAttribute).GetConstructor(new[] { typeof(string) }), new[] { "f9c2d51d-4f44-45f0-9eda-c9d599b58257" })}); var moduleBuilder = assemblyBuilder.DefineDynamicModule("ParametersWithoutNames", "ParametersWithoutNames.dll"); var typeBuilder = moduleBuilder.DefineType("I1", TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Import | TypeAttributes.Interface); typeBuilder.SetCustomAttribute(new CustomAttributeBuilder(typeof(GuidAttribute).GetConstructor(new[] { typeof(string) }), new[] { "f9c2d51d-4f44-45f0-9eda-c9d599b58277" })); var methodBuilder = typeBuilder.DefineMethod("M1", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.HideBySig, typeof(void), new[] { typeof(int), typeof(int), typeof(int) }); methodBuilder.DefineParameter(2, ParameterAttributes.Optional, null); methodBuilder.DefineParameter(3, ParameterAttributes.None, ""); typeBuilder.CreateType(); assemblyBuilder.Save(@"ParametersWithoutNames.dll"); } }
// Licensed to the .NET Foundation under one or more 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.Reflection; using System.Reflection.Emit; using System.Runtime.InteropServices; class Program { /// <summary> /// Compile and run this program to generate ParametersWithoutNames.dll /// </summary> static void Main() { var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("ParametersWithoutNames"), AssemblyBuilderAccess.Save, new[] { new CustomAttributeBuilder(typeof(ImportedFromTypeLibAttribute).GetConstructor(new[] { typeof(string) }), new[] { "GeneralPIA.dll" }), new CustomAttributeBuilder(typeof(GuidAttribute).GetConstructor(new[] { typeof(string) }), new[] { "f9c2d51d-4f44-45f0-9eda-c9d599b58257" })}); var moduleBuilder = assemblyBuilder.DefineDynamicModule("ParametersWithoutNames", "ParametersWithoutNames.dll"); var typeBuilder = moduleBuilder.DefineType("I1", TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Import | TypeAttributes.Interface); typeBuilder.SetCustomAttribute(new CustomAttributeBuilder(typeof(GuidAttribute).GetConstructor(new[] { typeof(string) }), new[] { "f9c2d51d-4f44-45f0-9eda-c9d599b58277" })); var methodBuilder = typeBuilder.DefineMethod("M1", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.HideBySig, typeof(void), new[] { typeof(int), typeof(int), typeof(int) }); methodBuilder.DefineParameter(2, ParameterAttributes.Optional, null); methodBuilder.DefineParameter(3, ParameterAttributes.None, ""); typeBuilder.CreateType(); assemblyBuilder.Save(@"ParametersWithoutNames.dll"); } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Compilers/Core/CodeAnalysisTest/CryptoBlobParserTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Roslyn.Test.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Security.Cryptography; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class CryptoBlobParserTests : TestBase { private const int HEADER_LEN = 20; private const int MOD_LEN = 128; private const int HALF_LEN = 64; [Fact] public void GetPrivateKeyFromKeyPair() { var key = ImmutableArray.Create(TestResources.General.snKey); RSAParameters? privateKeyOpt; Assert.True(CryptoBlobParser.TryParseKey(key, out _, out privateKeyOpt)); Debug.Assert(privateKeyOpt.HasValue); var privKey = privateKeyOpt.Value; AssertEx.Equal(privKey.Exponent, new byte[] { 0x01, 0x00, 0x01 }); var expectedModulus = key.Skip(HEADER_LEN).Take(MOD_LEN).ToArray(); Array.Reverse(expectedModulus); AssertEx.Equal(expectedModulus, privKey.Modulus); var expectedP = key.Skip(HEADER_LEN + MOD_LEN).Take(HALF_LEN).ToArray(); Array.Reverse(expectedP); AssertEx.Equal(expectedP, privKey.P); var expectedQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN).Take(HALF_LEN).ToArray(); Array.Reverse(expectedQ); AssertEx.Equal(expectedQ, privKey.Q); var expectedDP = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 2).Take(HALF_LEN).ToArray(); Array.Reverse(expectedDP); AssertEx.Equal(expectedDP, privKey.DP); var expectedDQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 3).Take(HALF_LEN).ToArray(); Array.Reverse(expectedDQ); AssertEx.Equal(expectedDQ, privKey.DQ); var expectedInverseQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 4).Take(HALF_LEN).ToArray(); Array.Reverse(expectedInverseQ); AssertEx.Equal(expectedInverseQ, privKey.InverseQ); var expectedD = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 5).Take(MOD_LEN).ToArray(); Array.Reverse(expectedD); AssertEx.Equal(expectedD, privKey.D); Assert.True(key.Skip(HEADER_LEN + MOD_LEN * 2 + HALF_LEN * 5).ToArray().Length == 0); } [Fact] public void GetPrivateKeyFromKeyPair2() { var key = ImmutableArray.Create(TestResources.General.snKey2); RSAParameters? privateKeyOpt; Assert.True(CryptoBlobParser.TryParseKey(key, out _, out privateKeyOpt)); Assert.True(privateKeyOpt.HasValue); var privKey = privateKeyOpt.Value; AssertEx.Equal(privKey.Exponent, new byte[] { 0x01, 0x00, 0x01 }); var expectedModulus = key.Skip(HEADER_LEN).Take(MOD_LEN).ToArray(); Array.Reverse(expectedModulus); AssertEx.Equal(expectedModulus, privKey.Modulus); var expectedP = key.Skip(HEADER_LEN + MOD_LEN).Take(HALF_LEN).ToArray(); Array.Reverse(expectedP); AssertEx.Equal(expectedP, privKey.P); var expectedQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN).Take(HALF_LEN).ToArray(); Array.Reverse(expectedQ); AssertEx.Equal(expectedQ, privKey.Q); var expectedDP = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 2).Take(HALF_LEN).ToArray(); Array.Reverse(expectedDP); AssertEx.Equal(expectedDP, privKey.DP); var expectedDQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 3).Take(HALF_LEN).ToArray(); Array.Reverse(expectedDQ); AssertEx.Equal(expectedDQ, privKey.DQ); var expectedInverseQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 4).Take(HALF_LEN).ToArray(); Array.Reverse(expectedInverseQ); AssertEx.Equal(expectedInverseQ, privKey.InverseQ); var expectedD = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 5).Take(MOD_LEN).ToArray(); Array.Reverse(expectedD); AssertEx.Equal(expectedD, privKey.D); Assert.True(key.Skip(HEADER_LEN + MOD_LEN * 2 + HALF_LEN * 5).ToArray().Length == 0); } [Fact] public void GetPublicKeyFromKeyPair() { var key = ImmutableArray.Create(TestResources.General.snKey); ImmutableArray<byte> pubKey; Assert.True(CryptoBlobParser.TryParseKey(key, out pubKey, out _)); Assert.True(CryptoBlobParser.IsValidPublicKey(pubKey)); AssertEx.Equal(TestResources.General.snPublicKey, pubKey); } [Fact] public void GetPublicKeyFromKeyPair2() { var key = ImmutableArray.Create(TestResources.General.snKey2); ImmutableArray<byte> pubKey; Assert.True(CryptoBlobParser.TryParseKey(key, out pubKey, out _)); Assert.True(CryptoBlobParser.IsValidPublicKey(pubKey)); AssertEx.Equal(TestResources.General.snPublicKey2, pubKey); } [Fact] public void SnPublicKeyIsReturnedAsIs() { var key = ImmutableArray.Create(TestResources.General.snPublicKey); ImmutableArray<byte> pubKey; Assert.True(CryptoBlobParser.TryParseKey(key, out pubKey, out _)); Assert.True(CryptoBlobParser.IsValidPublicKey(pubKey)); AssertEx.Equal(key, pubKey); } [Fact] public void GetSnPublicKeyFromPublicKeyBlob() { // A Strongname public key blob includes an additional header on top // of the wincrypt.h public key blob var snBlob = TestResources.General.snPublicKey; var buf = new byte[snBlob.Length - CryptoBlobParser.s_publicKeyHeaderSize]; Array.Copy(snBlob, CryptoBlobParser.s_publicKeyHeaderSize, buf, 0, buf.Length); var publicKeyBlob = ImmutableArray.Create(buf); ImmutableArray<byte> pubKey; Assert.True(CryptoBlobParser.TryParseKey(publicKeyBlob, out pubKey, out _)); Assert.True(CryptoBlobParser.IsValidPublicKey(pubKey)); AssertEx.Equal(snBlob, pubKey); } [Fact] public void TryGetPublicKeyFailsForInvalidKeyBlobs() { var invalidKeyBlobs = new[] { string.Empty, new string('0', 160 * 2), // 160 * 2 - the length of a public key, 2 - 2 chars per byte new string('0', 596 * 2), // 596 * 2 - the length of a key pair, 2 - 2 chars per byte "0702000000240000DEADBEEF" + new string('0', 584 * 2), // private key blob without magic private key "0602000000240000DEADBEEF" + new string('0', 136 * 2), // public key blob without magic public key }; Assert.False(CryptoBlobParser.TryParseKey(HexToBin(invalidKeyBlobs[0]), out _, out _)); Assert.False(CryptoBlobParser.TryParseKey(HexToBin(invalidKeyBlobs[1]), out _, out _)); Assert.False(CryptoBlobParser.TryParseKey(HexToBin(invalidKeyBlobs[2]), out _, out _)); Assert.False(CryptoBlobParser.TryParseKey(HexToBin(invalidKeyBlobs[3]), out _, out _)); } private static ImmutableArray<byte> HexToBin(string input) { Assert.True(input != null && (input.Length & 1) == 0, "invalid input string."); var result = new byte[input.Length >> 1]; for (var i = 0; i < result.Length; i++) { result[i] = byte.Parse(input.Substring(i << 1, 2), NumberStyles.HexNumber); } return ImmutableArray.Create(result); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Roslyn.Test.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Security.Cryptography; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class CryptoBlobParserTests : TestBase { private const int HEADER_LEN = 20; private const int MOD_LEN = 128; private const int HALF_LEN = 64; [Fact] public void GetPrivateKeyFromKeyPair() { var key = ImmutableArray.Create(TestResources.General.snKey); RSAParameters? privateKeyOpt; Assert.True(CryptoBlobParser.TryParseKey(key, out _, out privateKeyOpt)); Debug.Assert(privateKeyOpt.HasValue); var privKey = privateKeyOpt.Value; AssertEx.Equal(privKey.Exponent, new byte[] { 0x01, 0x00, 0x01 }); var expectedModulus = key.Skip(HEADER_LEN).Take(MOD_LEN).ToArray(); Array.Reverse(expectedModulus); AssertEx.Equal(expectedModulus, privKey.Modulus); var expectedP = key.Skip(HEADER_LEN + MOD_LEN).Take(HALF_LEN).ToArray(); Array.Reverse(expectedP); AssertEx.Equal(expectedP, privKey.P); var expectedQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN).Take(HALF_LEN).ToArray(); Array.Reverse(expectedQ); AssertEx.Equal(expectedQ, privKey.Q); var expectedDP = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 2).Take(HALF_LEN).ToArray(); Array.Reverse(expectedDP); AssertEx.Equal(expectedDP, privKey.DP); var expectedDQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 3).Take(HALF_LEN).ToArray(); Array.Reverse(expectedDQ); AssertEx.Equal(expectedDQ, privKey.DQ); var expectedInverseQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 4).Take(HALF_LEN).ToArray(); Array.Reverse(expectedInverseQ); AssertEx.Equal(expectedInverseQ, privKey.InverseQ); var expectedD = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 5).Take(MOD_LEN).ToArray(); Array.Reverse(expectedD); AssertEx.Equal(expectedD, privKey.D); Assert.True(key.Skip(HEADER_LEN + MOD_LEN * 2 + HALF_LEN * 5).ToArray().Length == 0); } [Fact] public void GetPrivateKeyFromKeyPair2() { var key = ImmutableArray.Create(TestResources.General.snKey2); RSAParameters? privateKeyOpt; Assert.True(CryptoBlobParser.TryParseKey(key, out _, out privateKeyOpt)); Assert.True(privateKeyOpt.HasValue); var privKey = privateKeyOpt.Value; AssertEx.Equal(privKey.Exponent, new byte[] { 0x01, 0x00, 0x01 }); var expectedModulus = key.Skip(HEADER_LEN).Take(MOD_LEN).ToArray(); Array.Reverse(expectedModulus); AssertEx.Equal(expectedModulus, privKey.Modulus); var expectedP = key.Skip(HEADER_LEN + MOD_LEN).Take(HALF_LEN).ToArray(); Array.Reverse(expectedP); AssertEx.Equal(expectedP, privKey.P); var expectedQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN).Take(HALF_LEN).ToArray(); Array.Reverse(expectedQ); AssertEx.Equal(expectedQ, privKey.Q); var expectedDP = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 2).Take(HALF_LEN).ToArray(); Array.Reverse(expectedDP); AssertEx.Equal(expectedDP, privKey.DP); var expectedDQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 3).Take(HALF_LEN).ToArray(); Array.Reverse(expectedDQ); AssertEx.Equal(expectedDQ, privKey.DQ); var expectedInverseQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 4).Take(HALF_LEN).ToArray(); Array.Reverse(expectedInverseQ); AssertEx.Equal(expectedInverseQ, privKey.InverseQ); var expectedD = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 5).Take(MOD_LEN).ToArray(); Array.Reverse(expectedD); AssertEx.Equal(expectedD, privKey.D); Assert.True(key.Skip(HEADER_LEN + MOD_LEN * 2 + HALF_LEN * 5).ToArray().Length == 0); } [Fact] public void GetPublicKeyFromKeyPair() { var key = ImmutableArray.Create(TestResources.General.snKey); ImmutableArray<byte> pubKey; Assert.True(CryptoBlobParser.TryParseKey(key, out pubKey, out _)); Assert.True(CryptoBlobParser.IsValidPublicKey(pubKey)); AssertEx.Equal(TestResources.General.snPublicKey, pubKey); } [Fact] public void GetPublicKeyFromKeyPair2() { var key = ImmutableArray.Create(TestResources.General.snKey2); ImmutableArray<byte> pubKey; Assert.True(CryptoBlobParser.TryParseKey(key, out pubKey, out _)); Assert.True(CryptoBlobParser.IsValidPublicKey(pubKey)); AssertEx.Equal(TestResources.General.snPublicKey2, pubKey); } [Fact] public void SnPublicKeyIsReturnedAsIs() { var key = ImmutableArray.Create(TestResources.General.snPublicKey); ImmutableArray<byte> pubKey; Assert.True(CryptoBlobParser.TryParseKey(key, out pubKey, out _)); Assert.True(CryptoBlobParser.IsValidPublicKey(pubKey)); AssertEx.Equal(key, pubKey); } [Fact] public void GetSnPublicKeyFromPublicKeyBlob() { // A Strongname public key blob includes an additional header on top // of the wincrypt.h public key blob var snBlob = TestResources.General.snPublicKey; var buf = new byte[snBlob.Length - CryptoBlobParser.s_publicKeyHeaderSize]; Array.Copy(snBlob, CryptoBlobParser.s_publicKeyHeaderSize, buf, 0, buf.Length); var publicKeyBlob = ImmutableArray.Create(buf); ImmutableArray<byte> pubKey; Assert.True(CryptoBlobParser.TryParseKey(publicKeyBlob, out pubKey, out _)); Assert.True(CryptoBlobParser.IsValidPublicKey(pubKey)); AssertEx.Equal(snBlob, pubKey); } [Fact] public void TryGetPublicKeyFailsForInvalidKeyBlobs() { var invalidKeyBlobs = new[] { string.Empty, new string('0', 160 * 2), // 160 * 2 - the length of a public key, 2 - 2 chars per byte new string('0', 596 * 2), // 596 * 2 - the length of a key pair, 2 - 2 chars per byte "0702000000240000DEADBEEF" + new string('0', 584 * 2), // private key blob without magic private key "0602000000240000DEADBEEF" + new string('0', 136 * 2), // public key blob without magic public key }; Assert.False(CryptoBlobParser.TryParseKey(HexToBin(invalidKeyBlobs[0]), out _, out _)); Assert.False(CryptoBlobParser.TryParseKey(HexToBin(invalidKeyBlobs[1]), out _, out _)); Assert.False(CryptoBlobParser.TryParseKey(HexToBin(invalidKeyBlobs[2]), out _, out _)); Assert.False(CryptoBlobParser.TryParseKey(HexToBin(invalidKeyBlobs[3]), out _, out _)); } private static ImmutableArray<byte> HexToBin(string input) { Assert.True(input != null && (input.Length & 1) == 0, "invalid input string."); var result = new byte[input.Length >> 1]; for (var i = 0; i < result.Length; i++) { result[i] = byte.Parse(input.Substring(i << 1, 2), NumberStyles.HexNumber); } return ImmutableArray.Create(result); } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Compilers/CSharp/Test/Emit/Emit/BinaryCompatibility.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.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class BinaryCompatibility : EmitMetadataTestBase { [Fact] public void InvokeVirtualBoundToOriginal() { // A method invocation of a virtual method is statically bound by the C# language to // the original declaration of the virtual method, not the most derived override of // that method. The difference between these two choices is visible in the binary // compatibility behavior of the program at runtime (e.g. when executing the program // against a modified library). This test checks that we bind the invocation to the // virtual method, not the override. var lib0 = @" public class Base { public virtual void M() { System.Console.WriteLine(""Base0""); } } public class Derived : Base { public override void M() { System.Console.WriteLine(""Derived0""); } } "; var lib0Image = CreateCompilationWithMscorlib46(lib0, options: TestOptions.ReleaseDll, assemblyName: "lib").EmitToImageReference(); var lib1 = @" public class Base { public virtual void M() { System.Console.WriteLine(""Base1""); } } public class Derived : Base { public new virtual void M() { System.Console.WriteLine(""Derived1""); } } "; var lib1Image = CreateCompilationWithMscorlib46(lib1, options: TestOptions.ReleaseDll, assemblyName: "lib").EmitToImageReference(); var client = @" public class Client { public static void M() { Derived d = new Derived(); d.M(); } } "; var clientImage = CreateCompilationWithMscorlib46(client, references: new[] { lib0Image }, options: TestOptions.ReleaseDll).EmitToImageReference(); var program = @" public class Program { public static void Main() { Client.M(); } } "; var compilation = CreateCompilationWithMscorlib46(program, references: new[] { lib1Image, clientImage }, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @"Base1"); } } }
// Licensed to the .NET Foundation under one or more 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.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class BinaryCompatibility : EmitMetadataTestBase { [Fact] public void InvokeVirtualBoundToOriginal() { // A method invocation of a virtual method is statically bound by the C# language to // the original declaration of the virtual method, not the most derived override of // that method. The difference between these two choices is visible in the binary // compatibility behavior of the program at runtime (e.g. when executing the program // against a modified library). This test checks that we bind the invocation to the // virtual method, not the override. var lib0 = @" public class Base { public virtual void M() { System.Console.WriteLine(""Base0""); } } public class Derived : Base { public override void M() { System.Console.WriteLine(""Derived0""); } } "; var lib0Image = CreateCompilationWithMscorlib46(lib0, options: TestOptions.ReleaseDll, assemblyName: "lib").EmitToImageReference(); var lib1 = @" public class Base { public virtual void M() { System.Console.WriteLine(""Base1""); } } public class Derived : Base { public new virtual void M() { System.Console.WriteLine(""Derived1""); } } "; var lib1Image = CreateCompilationWithMscorlib46(lib1, options: TestOptions.ReleaseDll, assemblyName: "lib").EmitToImageReference(); var client = @" public class Client { public static void M() { Derived d = new Derived(); d.M(); } } "; var clientImage = CreateCompilationWithMscorlib46(client, references: new[] { lib0Image }, options: TestOptions.ReleaseDll).EmitToImageReference(); var program = @" public class Program { public static void Main() { Client.M(); } } "; var compilation = CreateCompilationWithMscorlib46(program, references: new[] { lib1Image, clientImage }, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @"Base1"); } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Workspaces/Core/Portable/Serialization/SerializerService_Reference.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.IO; using System.Linq; using System.Reflection.Metadata; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Serialization { internal partial class SerializerService { private const int MetadataFailed = int.MaxValue; private static readonly ConditionalWeakTable<Metadata, object> s_lifetimeMap = new(); public static Checksum CreateChecksum(MetadataReference reference, CancellationToken cancellationToken) { if (reference is PortableExecutableReference portable) { return CreatePortableExecutableReferenceChecksum(portable, cancellationToken); } throw ExceptionUtilities.UnexpectedValue(reference.GetType()); } private static bool IsAnalyzerReferenceWithShadowCopyLoader(AnalyzerFileReference reference) => reference.AssemblyLoader is ShadowCopyAnalyzerAssemblyLoader; public static Checksum CreateChecksum(AnalyzerReference reference, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken)) { switch (reference) { case AnalyzerFileReference file: writer.WriteString(file.FullPath); writer.WriteBoolean(IsAnalyzerReferenceWithShadowCopyLoader(file)); break; default: throw ExceptionUtilities.UnexpectedValue(reference); } } stream.Position = 0; return Checksum.Create(stream); } public virtual void WriteMetadataReferenceTo(MetadataReference reference, ObjectWriter writer, SolutionReplicationContext context, CancellationToken cancellationToken) { if (reference is PortableExecutableReference portable) { if (portable is ISupportTemporaryStorage supportTemporaryStorage) { if (TryWritePortableExecutableReferenceBackedByTemporaryStorageTo(supportTemporaryStorage, writer, context, cancellationToken)) { return; } } WritePortableExecutableReferenceTo(portable, writer, cancellationToken); return; } throw ExceptionUtilities.UnexpectedValue(reference.GetType()); } public virtual MetadataReference ReadMetadataReferenceFrom(ObjectReader reader, CancellationToken cancellationToken) { var type = reader.ReadString(); if (type == nameof(PortableExecutableReference)) { return ReadPortableExecutableReferenceFrom(reader, cancellationToken); } throw ExceptionUtilities.UnexpectedValue(type); } public virtual void WriteAnalyzerReferenceTo(AnalyzerReference reference, ObjectWriter writer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); switch (reference) { case AnalyzerFileReference file: writer.WriteString(nameof(AnalyzerFileReference)); writer.WriteString(file.FullPath); writer.WriteBoolean(IsAnalyzerReferenceWithShadowCopyLoader(file)); break; default: throw ExceptionUtilities.UnexpectedValue(reference); } } public virtual AnalyzerReference ReadAnalyzerReferenceFrom(ObjectReader reader, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var type = reader.ReadString(); if (type == nameof(AnalyzerFileReference)) { var fullPath = reader.ReadString(); var shadowCopy = reader.ReadBoolean(); return new AnalyzerFileReference(fullPath, _analyzerLoaderProvider.GetLoader(new AnalyzerAssemblyLoaderOptions(shadowCopy))); } throw ExceptionUtilities.UnexpectedValue(type); } protected static void WritePortableExecutableReferenceHeaderTo( PortableExecutableReference reference, SerializationKinds kind, ObjectWriter writer, CancellationToken cancellationToken) { writer.WriteString(nameof(PortableExecutableReference)); writer.WriteInt32((int)kind); WritePortableExecutableReferencePropertiesTo(reference, writer, cancellationToken); } private static void WritePortableExecutableReferencePropertiesTo(PortableExecutableReference reference, ObjectWriter writer, CancellationToken cancellationToken) { WriteTo(reference.Properties, writer, cancellationToken); writer.WriteString(reference.FilePath); } private static Checksum CreatePortableExecutableReferenceChecksum(PortableExecutableReference reference, CancellationToken cancellationToken) { using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken)) { WritePortableExecutableReferencePropertiesTo(reference, writer, cancellationToken); WriteMvidsTo(TryGetMetadata(reference), writer, cancellationToken); } stream.Position = 0; return Checksum.Create(stream); } private static void WriteMvidsTo(Metadata? metadata, ObjectWriter writer, CancellationToken cancellationToken) { if (metadata == null) { // handle error case where we couldn't load metadata of the reference. // this basically won't write anything to writer return; } if (metadata is AssemblyMetadata assemblyMetadata) { if (!TryGetModules(assemblyMetadata, out var modules)) { // Gracefully bail out without writing anything to the writer. return; } writer.WriteInt32((int)assemblyMetadata.Kind); writer.WriteInt32(modules.Length); foreach (var module in modules) { WriteMvidTo(module, writer, cancellationToken); } return; } WriteMvidTo((ModuleMetadata)metadata, writer, cancellationToken); } private static bool TryGetModules(AssemblyMetadata assemblyMetadata, out ImmutableArray<ModuleMetadata> modules) { // Gracefully handle documented exceptions from 'GetModules' invocation. try { modules = assemblyMetadata.GetModules(); return true; } catch (Exception ex) when (ex is BadImageFormatException || ex is IOException || ex is ObjectDisposedException) { modules = default; return false; } } private static void WriteMvidTo(ModuleMetadata metadata, ObjectWriter writer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); writer.WriteInt32((int)metadata.Kind); var metadataReader = metadata.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; var guid = metadataReader.GetGuid(mvidHandle); writer.WriteGuid(guid); } private static void WritePortableExecutableReferenceTo( PortableExecutableReference reference, ObjectWriter writer, CancellationToken cancellationToken) { WritePortableExecutableReferenceHeaderTo(reference, SerializationKinds.Bits, writer, cancellationToken); WriteTo(TryGetMetadata(reference), writer, cancellationToken); // TODO: what I should do with documentation provider? it is not exposed outside } private PortableExecutableReference ReadPortableExecutableReferenceFrom(ObjectReader reader, CancellationToken cancellationToken) { var kind = (SerializationKinds)reader.ReadInt32(); if (kind == SerializationKinds.Bits || kind == SerializationKinds.MemoryMapFile) { var properties = ReadMetadataReferencePropertiesFrom(reader, cancellationToken); var filePath = reader.ReadString(); var tuple = TryReadMetadataFrom(reader, kind, cancellationToken); if (tuple == null) { // TODO: deal with xml document provider properly // should we shadow copy xml doc comment? // image doesn't exist return new MissingMetadataReference(properties, filePath, XmlDocumentationProvider.Default); } // for now, we will use IDocumentationProviderService to get DocumentationProvider for metadata // references. if the service is not available, then use Default (NoOp) provider. // since xml doc comment is not part of solution snapshot, (like xml reference resolver or strong name // provider) this provider can also potentially provide content that is different than one in the host. // an alternative approach of this is synching content of xml doc comment to remote host as well // so that we can put xml doc comment as part of snapshot. but until we believe that is necessary, // it will go with simpler approach var documentProvider = filePath != null && _documentationService != null ? _documentationService.GetDocumentationProvider(filePath) : XmlDocumentationProvider.Default; return new SerializedMetadataReference( properties, filePath, tuple.Value.metadata, tuple.Value.storages, documentProvider); } throw ExceptionUtilities.UnexpectedValue(kind); } private static void WriteTo(MetadataReferenceProperties properties, ObjectWriter writer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); writer.WriteInt32((int)properties.Kind); writer.WriteValue(properties.Aliases.ToArray()); writer.WriteBoolean(properties.EmbedInteropTypes); } private static MetadataReferenceProperties ReadMetadataReferencePropertiesFrom(ObjectReader reader, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var kind = (MetadataImageKind)reader.ReadInt32(); var aliases = reader.ReadArray<string>().ToImmutableArrayOrEmpty(); var embedInteropTypes = reader.ReadBoolean(); return new MetadataReferenceProperties(kind, aliases, embedInteropTypes); } private static void WriteTo(Metadata? metadata, ObjectWriter writer, CancellationToken cancellationToken) { if (metadata == null) { // handle error case where metadata failed to load writer.WriteInt32(MetadataFailed); return; } if (metadata is AssemblyMetadata assemblyMetadata) { if (!TryGetModules(assemblyMetadata, out var modules)) { // Gracefully handle error case where unable to get modules. writer.WriteInt32(MetadataFailed); return; } writer.WriteInt32((int)assemblyMetadata.Kind); writer.WriteInt32(modules.Length); foreach (var module in modules) { WriteTo(module, writer, cancellationToken); } return; } WriteTo((ModuleMetadata)metadata, writer, cancellationToken); } private static bool TryWritePortableExecutableReferenceBackedByTemporaryStorageTo( ISupportTemporaryStorage reference, ObjectWriter writer, SolutionReplicationContext context, CancellationToken cancellationToken) { var storages = reference.GetStorages(); if (storages == null) { return false; } // Not clear if name should be allowed to be null here (https://github.com/dotnet/roslyn/issues/43037) using var pooled = Creator.CreateList<(string? name, long offset, long size)>(); foreach (var storage in storages) { if (storage is not ITemporaryStorageWithName storage2) { return false; } context.AddResource(storage); pooled.Object.Add((storage2.Name, storage2.Offset, storage2.Size)); } WritePortableExecutableReferenceHeaderTo((PortableExecutableReference)reference, SerializationKinds.MemoryMapFile, writer, cancellationToken); writer.WriteInt32((int)MetadataImageKind.Assembly); writer.WriteInt32(pooled.Object.Count); foreach (var (name, offset, size) in pooled.Object) { writer.WriteInt32((int)MetadataImageKind.Module); writer.WriteString(name); writer.WriteInt64(offset); writer.WriteInt64(size); } return true; } private (Metadata metadata, ImmutableArray<ITemporaryStreamStorage> storages)? TryReadMetadataFrom( ObjectReader reader, SerializationKinds kind, CancellationToken cancellationToken) { var imageKind = reader.ReadInt32(); if (imageKind == MetadataFailed) { // error case return null; } var metadataKind = (MetadataImageKind)imageKind; if (_storageService == null) { if (metadataKind == MetadataImageKind.Assembly) { using var pooledMetadata = Creator.CreateList<ModuleMetadata>(); var count = reader.ReadInt32(); for (var i = 0; i < count; i++) { metadataKind = (MetadataImageKind)reader.ReadInt32(); Contract.ThrowIfFalse(metadataKind == MetadataImageKind.Module); #pragma warning disable CA2016 // https://github.com/dotnet/roslyn-analyzers/issues/4985 pooledMetadata.Object.Add(ReadModuleMetadataFrom(reader, kind)); #pragma warning restore CA2016 } return (AssemblyMetadata.Create(pooledMetadata.Object), storages: default); } Contract.ThrowIfFalse(metadataKind == MetadataImageKind.Module); #pragma warning disable CA2016 // https://github.com/dotnet/roslyn-analyzers/issues/4985 return (ReadModuleMetadataFrom(reader, kind), storages: default); #pragma warning restore CA2016 } if (metadataKind == MetadataImageKind.Assembly) { using var pooledMetadata = Creator.CreateList<ModuleMetadata>(); using var pooledStorage = Creator.CreateList<ITemporaryStreamStorage>(); var count = reader.ReadInt32(); for (var i = 0; i < count; i++) { metadataKind = (MetadataImageKind)reader.ReadInt32(); Contract.ThrowIfFalse(metadataKind == MetadataImageKind.Module); var (metadata, storage) = ReadModuleMetadataFrom(reader, kind, cancellationToken); pooledMetadata.Object.Add(metadata); pooledStorage.Object.Add(storage); } return (AssemblyMetadata.Create(pooledMetadata.Object), pooledStorage.Object.ToImmutableArrayOrEmpty()); } Contract.ThrowIfFalse(metadataKind == MetadataImageKind.Module); var moduleInfo = ReadModuleMetadataFrom(reader, kind, cancellationToken); return (moduleInfo.metadata, ImmutableArray.Create(moduleInfo.storage)); } private (ModuleMetadata metadata, ITemporaryStreamStorage storage) ReadModuleMetadataFrom( ObjectReader reader, SerializationKinds kind, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); GetTemporaryStorage(reader, kind, out var storage, out var length, cancellationToken); var storageStream = storage.ReadStream(cancellationToken); Contract.ThrowIfFalse(length == storageStream.Length); GetMetadata(storageStream, length, out var metadata, out var lifeTimeObject); // make sure we keep storageStream alive while Metadata is alive // we use conditional weak table since we can't control metadata liftetime s_lifetimeMap.Add(metadata, lifeTimeObject); return (metadata, storage); } private static ModuleMetadata ReadModuleMetadataFrom(ObjectReader reader, SerializationKinds kind) { Contract.ThrowIfFalse(SerializationKinds.Bits == kind); var array = reader.ReadArray<byte>(); var pinnedObject = new PinnedObject(array); var metadata = ModuleMetadata.CreateFromMetadata(pinnedObject.GetPointer(), array.Length); // make sure we keep storageStream alive while Metadata is alive // we use conditional weak table since we can't control metadata liftetime s_lifetimeMap.Add(metadata, pinnedObject); return metadata; } private void GetTemporaryStorage( ObjectReader reader, SerializationKinds kind, out ITemporaryStreamStorage storage, out long length, CancellationToken cancellationToken) { if (kind == SerializationKinds.Bits) { storage = _storageService.CreateTemporaryStreamStorage(cancellationToken); using var stream = SerializableBytes.CreateWritableStream(); CopyByteArrayToStream(reader, stream, cancellationToken); length = stream.Length; stream.Position = 0; storage.WriteStream(stream, cancellationToken); return; } if (kind == SerializationKinds.MemoryMapFile) { var service2 = (ITemporaryStorageService2)_storageService; var name = reader.ReadString(); var offset = reader.ReadInt64(); var size = reader.ReadInt64(); storage = service2.AttachTemporaryStreamStorage(name, offset, size, cancellationToken); length = size; return; } throw ExceptionUtilities.UnexpectedValue(kind); } private static void GetMetadata(Stream stream, long length, out ModuleMetadata metadata, out object lifeTimeObject) { if (stream is ISupportDirectMemoryAccess directAccess) { metadata = ModuleMetadata.CreateFromMetadata(directAccess.GetPointer(), (int)length); lifeTimeObject = stream; return; } PinnedObject pinnedObject; if (stream is MemoryStream memory && memory.TryGetBuffer(out var buffer) && buffer.Offset == 0) { pinnedObject = new PinnedObject(buffer.Array!); } else { var array = new byte[length]; stream.Read(array, 0, (int)length); pinnedObject = new PinnedObject(array); } metadata = ModuleMetadata.CreateFromMetadata(pinnedObject.GetPointer(), (int)length); lifeTimeObject = pinnedObject; } private static void CopyByteArrayToStream(ObjectReader reader, Stream stream, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // TODO: make reader be able to read byte[] chunk var content = reader.ReadArray<byte>(); stream.Write(content, 0, content.Length); } private static void WriteTo(ModuleMetadata metadata, ObjectWriter writer, CancellationToken cancellationToken) { writer.WriteInt32((int)metadata.Kind); WriteTo(metadata.GetMetadataReader(), writer, cancellationToken); } private static unsafe void WriteTo(MetadataReader reader, ObjectWriter writer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); writer.WriteValue(new ReadOnlySpan<byte>(reader.MetadataPointer, reader.MetadataLength)); } private static void WriteUnresolvedAnalyzerReferenceTo(AnalyzerReference reference, ObjectWriter writer) { writer.WriteString(nameof(UnresolvedAnalyzerReference)); writer.WriteString(reference.FullPath); } private static Metadata? TryGetMetadata(PortableExecutableReference reference) { try { return reference.GetMetadata(); } catch { // we have a reference but the file the reference is pointing to // might not actually exist on disk. // in that case, rather than crashing, we will handle it gracefully. return null; } } private sealed class PinnedObject : IDisposable { // shouldn't be read-only since GCHandle is a mutable struct private GCHandle _gcHandle; public PinnedObject(byte[] array) => _gcHandle = GCHandle.Alloc(array, GCHandleType.Pinned); internal IntPtr GetPointer() => _gcHandle.AddrOfPinnedObject(); private void OnDispose() { if (_gcHandle.IsAllocated) { _gcHandle.Free(); } } ~PinnedObject() => OnDispose(); public void Dispose() { GC.SuppressFinalize(this); OnDispose(); } } private sealed class MissingMetadataReference : PortableExecutableReference { private readonly DocumentationProvider _provider; public MissingMetadataReference( MetadataReferenceProperties properties, string? fullPath, DocumentationProvider initialDocumentation) : base(properties, fullPath, initialDocumentation) { // TODO: doc comment provider is a bit weird. _provider = initialDocumentation; } protected override DocumentationProvider CreateDocumentationProvider() { // TODO: properly implement this throw new NotImplementedException(); } protected override Metadata GetMetadataImpl() { // we just throw "FileNotFoundException" even if it might not be actual reason // why metadata has failed to load. in this context, we don't care much on actual // reason. we just need to maintain failure when re-constructing solution to maintain // snapshot integrity. // // if anyone care actual reason, he should get that info from original Solution. throw new FileNotFoundException(FilePath); } protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties) => new MissingMetadataReference(properties, FilePath, _provider); } [DebuggerDisplay("{" + nameof(Display) + ",nq}")] private sealed class SerializedMetadataReference : PortableExecutableReference, ISupportTemporaryStorage { private readonly Metadata _metadata; private readonly ImmutableArray<ITemporaryStreamStorage> _storagesOpt; private readonly DocumentationProvider _provider; public SerializedMetadataReference( MetadataReferenceProperties properties, string? fullPath, Metadata metadata, ImmutableArray<ITemporaryStreamStorage> storagesOpt, DocumentationProvider initialDocumentation) : base(properties, fullPath, initialDocumentation) { _metadata = metadata; _storagesOpt = storagesOpt; _provider = initialDocumentation; } protected override DocumentationProvider CreateDocumentationProvider() { // this uses documentation provider given at the constructor throw ExceptionUtilities.Unreachable; } protected override Metadata GetMetadataImpl() => _metadata; protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties) => new SerializedMetadataReference(properties, FilePath, _metadata, _storagesOpt, _provider); public IEnumerable<ITemporaryStreamStorage>? GetStorages() => _storagesOpt.IsDefault ? (IEnumerable<ITemporaryStreamStorage>?)null : _storagesOpt; } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Reflection.Metadata; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Serialization { internal partial class SerializerService { private const int MetadataFailed = int.MaxValue; private static readonly ConditionalWeakTable<Metadata, object> s_lifetimeMap = new(); public static Checksum CreateChecksum(MetadataReference reference, CancellationToken cancellationToken) { if (reference is PortableExecutableReference portable) { return CreatePortableExecutableReferenceChecksum(portable, cancellationToken); } throw ExceptionUtilities.UnexpectedValue(reference.GetType()); } private static bool IsAnalyzerReferenceWithShadowCopyLoader(AnalyzerFileReference reference) => reference.AssemblyLoader is ShadowCopyAnalyzerAssemblyLoader; public static Checksum CreateChecksum(AnalyzerReference reference, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken)) { switch (reference) { case AnalyzerFileReference file: writer.WriteString(file.FullPath); writer.WriteBoolean(IsAnalyzerReferenceWithShadowCopyLoader(file)); break; default: throw ExceptionUtilities.UnexpectedValue(reference); } } stream.Position = 0; return Checksum.Create(stream); } public virtual void WriteMetadataReferenceTo(MetadataReference reference, ObjectWriter writer, SolutionReplicationContext context, CancellationToken cancellationToken) { if (reference is PortableExecutableReference portable) { if (portable is ISupportTemporaryStorage supportTemporaryStorage) { if (TryWritePortableExecutableReferenceBackedByTemporaryStorageTo(supportTemporaryStorage, writer, context, cancellationToken)) { return; } } WritePortableExecutableReferenceTo(portable, writer, cancellationToken); return; } throw ExceptionUtilities.UnexpectedValue(reference.GetType()); } public virtual MetadataReference ReadMetadataReferenceFrom(ObjectReader reader, CancellationToken cancellationToken) { var type = reader.ReadString(); if (type == nameof(PortableExecutableReference)) { return ReadPortableExecutableReferenceFrom(reader, cancellationToken); } throw ExceptionUtilities.UnexpectedValue(type); } public virtual void WriteAnalyzerReferenceTo(AnalyzerReference reference, ObjectWriter writer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); switch (reference) { case AnalyzerFileReference file: writer.WriteString(nameof(AnalyzerFileReference)); writer.WriteString(file.FullPath); writer.WriteBoolean(IsAnalyzerReferenceWithShadowCopyLoader(file)); break; default: throw ExceptionUtilities.UnexpectedValue(reference); } } public virtual AnalyzerReference ReadAnalyzerReferenceFrom(ObjectReader reader, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var type = reader.ReadString(); if (type == nameof(AnalyzerFileReference)) { var fullPath = reader.ReadString(); var shadowCopy = reader.ReadBoolean(); return new AnalyzerFileReference(fullPath, _analyzerLoaderProvider.GetLoader(new AnalyzerAssemblyLoaderOptions(shadowCopy))); } throw ExceptionUtilities.UnexpectedValue(type); } protected static void WritePortableExecutableReferenceHeaderTo( PortableExecutableReference reference, SerializationKinds kind, ObjectWriter writer, CancellationToken cancellationToken) { writer.WriteString(nameof(PortableExecutableReference)); writer.WriteInt32((int)kind); WritePortableExecutableReferencePropertiesTo(reference, writer, cancellationToken); } private static void WritePortableExecutableReferencePropertiesTo(PortableExecutableReference reference, ObjectWriter writer, CancellationToken cancellationToken) { WriteTo(reference.Properties, writer, cancellationToken); writer.WriteString(reference.FilePath); } private static Checksum CreatePortableExecutableReferenceChecksum(PortableExecutableReference reference, CancellationToken cancellationToken) { using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken)) { WritePortableExecutableReferencePropertiesTo(reference, writer, cancellationToken); WriteMvidsTo(TryGetMetadata(reference), writer, cancellationToken); } stream.Position = 0; return Checksum.Create(stream); } private static void WriteMvidsTo(Metadata? metadata, ObjectWriter writer, CancellationToken cancellationToken) { if (metadata == null) { // handle error case where we couldn't load metadata of the reference. // this basically won't write anything to writer return; } if (metadata is AssemblyMetadata assemblyMetadata) { if (!TryGetModules(assemblyMetadata, out var modules)) { // Gracefully bail out without writing anything to the writer. return; } writer.WriteInt32((int)assemblyMetadata.Kind); writer.WriteInt32(modules.Length); foreach (var module in modules) { WriteMvidTo(module, writer, cancellationToken); } return; } WriteMvidTo((ModuleMetadata)metadata, writer, cancellationToken); } private static bool TryGetModules(AssemblyMetadata assemblyMetadata, out ImmutableArray<ModuleMetadata> modules) { // Gracefully handle documented exceptions from 'GetModules' invocation. try { modules = assemblyMetadata.GetModules(); return true; } catch (Exception ex) when (ex is BadImageFormatException || ex is IOException || ex is ObjectDisposedException) { modules = default; return false; } } private static void WriteMvidTo(ModuleMetadata metadata, ObjectWriter writer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); writer.WriteInt32((int)metadata.Kind); var metadataReader = metadata.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; var guid = metadataReader.GetGuid(mvidHandle); writer.WriteGuid(guid); } private static void WritePortableExecutableReferenceTo( PortableExecutableReference reference, ObjectWriter writer, CancellationToken cancellationToken) { WritePortableExecutableReferenceHeaderTo(reference, SerializationKinds.Bits, writer, cancellationToken); WriteTo(TryGetMetadata(reference), writer, cancellationToken); // TODO: what I should do with documentation provider? it is not exposed outside } private PortableExecutableReference ReadPortableExecutableReferenceFrom(ObjectReader reader, CancellationToken cancellationToken) { var kind = (SerializationKinds)reader.ReadInt32(); if (kind == SerializationKinds.Bits || kind == SerializationKinds.MemoryMapFile) { var properties = ReadMetadataReferencePropertiesFrom(reader, cancellationToken); var filePath = reader.ReadString(); var tuple = TryReadMetadataFrom(reader, kind, cancellationToken); if (tuple == null) { // TODO: deal with xml document provider properly // should we shadow copy xml doc comment? // image doesn't exist return new MissingMetadataReference(properties, filePath, XmlDocumentationProvider.Default); } // for now, we will use IDocumentationProviderService to get DocumentationProvider for metadata // references. if the service is not available, then use Default (NoOp) provider. // since xml doc comment is not part of solution snapshot, (like xml reference resolver or strong name // provider) this provider can also potentially provide content that is different than one in the host. // an alternative approach of this is synching content of xml doc comment to remote host as well // so that we can put xml doc comment as part of snapshot. but until we believe that is necessary, // it will go with simpler approach var documentProvider = filePath != null && _documentationService != null ? _documentationService.GetDocumentationProvider(filePath) : XmlDocumentationProvider.Default; return new SerializedMetadataReference( properties, filePath, tuple.Value.metadata, tuple.Value.storages, documentProvider); } throw ExceptionUtilities.UnexpectedValue(kind); } private static void WriteTo(MetadataReferenceProperties properties, ObjectWriter writer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); writer.WriteInt32((int)properties.Kind); writer.WriteValue(properties.Aliases.ToArray()); writer.WriteBoolean(properties.EmbedInteropTypes); } private static MetadataReferenceProperties ReadMetadataReferencePropertiesFrom(ObjectReader reader, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var kind = (MetadataImageKind)reader.ReadInt32(); var aliases = reader.ReadArray<string>().ToImmutableArrayOrEmpty(); var embedInteropTypes = reader.ReadBoolean(); return new MetadataReferenceProperties(kind, aliases, embedInteropTypes); } private static void WriteTo(Metadata? metadata, ObjectWriter writer, CancellationToken cancellationToken) { if (metadata == null) { // handle error case where metadata failed to load writer.WriteInt32(MetadataFailed); return; } if (metadata is AssemblyMetadata assemblyMetadata) { if (!TryGetModules(assemblyMetadata, out var modules)) { // Gracefully handle error case where unable to get modules. writer.WriteInt32(MetadataFailed); return; } writer.WriteInt32((int)assemblyMetadata.Kind); writer.WriteInt32(modules.Length); foreach (var module in modules) { WriteTo(module, writer, cancellationToken); } return; } WriteTo((ModuleMetadata)metadata, writer, cancellationToken); } private static bool TryWritePortableExecutableReferenceBackedByTemporaryStorageTo( ISupportTemporaryStorage reference, ObjectWriter writer, SolutionReplicationContext context, CancellationToken cancellationToken) { var storages = reference.GetStorages(); if (storages == null) { return false; } // Not clear if name should be allowed to be null here (https://github.com/dotnet/roslyn/issues/43037) using var pooled = Creator.CreateList<(string? name, long offset, long size)>(); foreach (var storage in storages) { if (storage is not ITemporaryStorageWithName storage2) { return false; } context.AddResource(storage); pooled.Object.Add((storage2.Name, storage2.Offset, storage2.Size)); } WritePortableExecutableReferenceHeaderTo((PortableExecutableReference)reference, SerializationKinds.MemoryMapFile, writer, cancellationToken); writer.WriteInt32((int)MetadataImageKind.Assembly); writer.WriteInt32(pooled.Object.Count); foreach (var (name, offset, size) in pooled.Object) { writer.WriteInt32((int)MetadataImageKind.Module); writer.WriteString(name); writer.WriteInt64(offset); writer.WriteInt64(size); } return true; } private (Metadata metadata, ImmutableArray<ITemporaryStreamStorage> storages)? TryReadMetadataFrom( ObjectReader reader, SerializationKinds kind, CancellationToken cancellationToken) { var imageKind = reader.ReadInt32(); if (imageKind == MetadataFailed) { // error case return null; } var metadataKind = (MetadataImageKind)imageKind; if (_storageService == null) { if (metadataKind == MetadataImageKind.Assembly) { using var pooledMetadata = Creator.CreateList<ModuleMetadata>(); var count = reader.ReadInt32(); for (var i = 0; i < count; i++) { metadataKind = (MetadataImageKind)reader.ReadInt32(); Contract.ThrowIfFalse(metadataKind == MetadataImageKind.Module); #pragma warning disable CA2016 // https://github.com/dotnet/roslyn-analyzers/issues/4985 pooledMetadata.Object.Add(ReadModuleMetadataFrom(reader, kind)); #pragma warning restore CA2016 } return (AssemblyMetadata.Create(pooledMetadata.Object), storages: default); } Contract.ThrowIfFalse(metadataKind == MetadataImageKind.Module); #pragma warning disable CA2016 // https://github.com/dotnet/roslyn-analyzers/issues/4985 return (ReadModuleMetadataFrom(reader, kind), storages: default); #pragma warning restore CA2016 } if (metadataKind == MetadataImageKind.Assembly) { using var pooledMetadata = Creator.CreateList<ModuleMetadata>(); using var pooledStorage = Creator.CreateList<ITemporaryStreamStorage>(); var count = reader.ReadInt32(); for (var i = 0; i < count; i++) { metadataKind = (MetadataImageKind)reader.ReadInt32(); Contract.ThrowIfFalse(metadataKind == MetadataImageKind.Module); var (metadata, storage) = ReadModuleMetadataFrom(reader, kind, cancellationToken); pooledMetadata.Object.Add(metadata); pooledStorage.Object.Add(storage); } return (AssemblyMetadata.Create(pooledMetadata.Object), pooledStorage.Object.ToImmutableArrayOrEmpty()); } Contract.ThrowIfFalse(metadataKind == MetadataImageKind.Module); var moduleInfo = ReadModuleMetadataFrom(reader, kind, cancellationToken); return (moduleInfo.metadata, ImmutableArray.Create(moduleInfo.storage)); } private (ModuleMetadata metadata, ITemporaryStreamStorage storage) ReadModuleMetadataFrom( ObjectReader reader, SerializationKinds kind, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); GetTemporaryStorage(reader, kind, out var storage, out var length, cancellationToken); var storageStream = storage.ReadStream(cancellationToken); Contract.ThrowIfFalse(length == storageStream.Length); GetMetadata(storageStream, length, out var metadata, out var lifeTimeObject); // make sure we keep storageStream alive while Metadata is alive // we use conditional weak table since we can't control metadata liftetime s_lifetimeMap.Add(metadata, lifeTimeObject); return (metadata, storage); } private static ModuleMetadata ReadModuleMetadataFrom(ObjectReader reader, SerializationKinds kind) { Contract.ThrowIfFalse(SerializationKinds.Bits == kind); var array = reader.ReadArray<byte>(); var pinnedObject = new PinnedObject(array); var metadata = ModuleMetadata.CreateFromMetadata(pinnedObject.GetPointer(), array.Length); // make sure we keep storageStream alive while Metadata is alive // we use conditional weak table since we can't control metadata liftetime s_lifetimeMap.Add(metadata, pinnedObject); return metadata; } private void GetTemporaryStorage( ObjectReader reader, SerializationKinds kind, out ITemporaryStreamStorage storage, out long length, CancellationToken cancellationToken) { if (kind == SerializationKinds.Bits) { storage = _storageService.CreateTemporaryStreamStorage(cancellationToken); using var stream = SerializableBytes.CreateWritableStream(); CopyByteArrayToStream(reader, stream, cancellationToken); length = stream.Length; stream.Position = 0; storage.WriteStream(stream, cancellationToken); return; } if (kind == SerializationKinds.MemoryMapFile) { var service2 = (ITemporaryStorageService2)_storageService; var name = reader.ReadString(); var offset = reader.ReadInt64(); var size = reader.ReadInt64(); storage = service2.AttachTemporaryStreamStorage(name, offset, size, cancellationToken); length = size; return; } throw ExceptionUtilities.UnexpectedValue(kind); } private static void GetMetadata(Stream stream, long length, out ModuleMetadata metadata, out object lifeTimeObject) { if (stream is ISupportDirectMemoryAccess directAccess) { metadata = ModuleMetadata.CreateFromMetadata(directAccess.GetPointer(), (int)length); lifeTimeObject = stream; return; } PinnedObject pinnedObject; if (stream is MemoryStream memory && memory.TryGetBuffer(out var buffer) && buffer.Offset == 0) { pinnedObject = new PinnedObject(buffer.Array!); } else { var array = new byte[length]; stream.Read(array, 0, (int)length); pinnedObject = new PinnedObject(array); } metadata = ModuleMetadata.CreateFromMetadata(pinnedObject.GetPointer(), (int)length); lifeTimeObject = pinnedObject; } private static void CopyByteArrayToStream(ObjectReader reader, Stream stream, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // TODO: make reader be able to read byte[] chunk var content = reader.ReadArray<byte>(); stream.Write(content, 0, content.Length); } private static void WriteTo(ModuleMetadata metadata, ObjectWriter writer, CancellationToken cancellationToken) { writer.WriteInt32((int)metadata.Kind); WriteTo(metadata.GetMetadataReader(), writer, cancellationToken); } private static unsafe void WriteTo(MetadataReader reader, ObjectWriter writer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); writer.WriteValue(new ReadOnlySpan<byte>(reader.MetadataPointer, reader.MetadataLength)); } private static void WriteUnresolvedAnalyzerReferenceTo(AnalyzerReference reference, ObjectWriter writer) { writer.WriteString(nameof(UnresolvedAnalyzerReference)); writer.WriteString(reference.FullPath); } private static Metadata? TryGetMetadata(PortableExecutableReference reference) { try { return reference.GetMetadata(); } catch { // we have a reference but the file the reference is pointing to // might not actually exist on disk. // in that case, rather than crashing, we will handle it gracefully. return null; } } private sealed class PinnedObject : IDisposable { // shouldn't be read-only since GCHandle is a mutable struct private GCHandle _gcHandle; public PinnedObject(byte[] array) => _gcHandle = GCHandle.Alloc(array, GCHandleType.Pinned); internal IntPtr GetPointer() => _gcHandle.AddrOfPinnedObject(); private void OnDispose() { if (_gcHandle.IsAllocated) { _gcHandle.Free(); } } ~PinnedObject() => OnDispose(); public void Dispose() { GC.SuppressFinalize(this); OnDispose(); } } private sealed class MissingMetadataReference : PortableExecutableReference { private readonly DocumentationProvider _provider; public MissingMetadataReference( MetadataReferenceProperties properties, string? fullPath, DocumentationProvider initialDocumentation) : base(properties, fullPath, initialDocumentation) { // TODO: doc comment provider is a bit weird. _provider = initialDocumentation; } protected override DocumentationProvider CreateDocumentationProvider() { // TODO: properly implement this throw new NotImplementedException(); } protected override Metadata GetMetadataImpl() { // we just throw "FileNotFoundException" even if it might not be actual reason // why metadata has failed to load. in this context, we don't care much on actual // reason. we just need to maintain failure when re-constructing solution to maintain // snapshot integrity. // // if anyone care actual reason, he should get that info from original Solution. throw new FileNotFoundException(FilePath); } protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties) => new MissingMetadataReference(properties, FilePath, _provider); } [DebuggerDisplay("{" + nameof(Display) + ",nq}")] private sealed class SerializedMetadataReference : PortableExecutableReference, ISupportTemporaryStorage { private readonly Metadata _metadata; private readonly ImmutableArray<ITemporaryStreamStorage> _storagesOpt; private readonly DocumentationProvider _provider; public SerializedMetadataReference( MetadataReferenceProperties properties, string? fullPath, Metadata metadata, ImmutableArray<ITemporaryStreamStorage> storagesOpt, DocumentationProvider initialDocumentation) : base(properties, fullPath, initialDocumentation) { _metadata = metadata; _storagesOpt = storagesOpt; _provider = initialDocumentation; } protected override DocumentationProvider CreateDocumentationProvider() { // this uses documentation provider given at the constructor throw ExceptionUtilities.Unreachable; } protected override Metadata GetMetadataImpl() => _metadata; protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties) => new SerializedMetadataReference(properties, FilePath, _metadata, _storagesOpt, _provider); public IEnumerable<ITemporaryStreamStorage>? GetStorages() => _storagesOpt.IsDefault ? (IEnumerable<ITemporaryStreamStorage>?)null : _storagesOpt; } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/EditorFeatures/Core/Shared/Extensions/IThreadingContextExtensions.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.Editor.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class IThreadingContextExtensions { public static void ThrowIfNotOnUIThread(this IThreadingContext threadingContext) => Contract.ThrowIfFalse(threadingContext.JoinableTaskContext.IsOnMainThread); } }
// Licensed to the .NET Foundation under one or more 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.Editor.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class IThreadingContextExtensions { public static void ThrowIfNotOnUIThread(this IThreadingContext threadingContext) => Contract.ThrowIfFalse(threadingContext.JoinableTaskContext.IsOnMainThread); } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Compilers/CSharp/Portable/Binder/SimpleProgramUnitBinder.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 Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This binder provides a context for binding within a specific compilation unit, but outside of top-level statements. /// It ensures that locals are in scope, however it is not responsible /// for creating the symbols. That task is actually owned by <see cref="SimpleProgramBinder"/> and /// this binder simply delegates to it when appropriate. That ensures that the same set of symbols is /// shared across all compilation units. /// </summary> internal sealed class SimpleProgramUnitBinder : LocalScopeBinder { private readonly SimpleProgramBinder _scope; public SimpleProgramUnitBinder(Binder enclosing, SimpleProgramBinder scope) : base(enclosing, enclosing.Flags) { _scope = scope; } protected override ImmutableArray<LocalSymbol> BuildLocals() { return _scope.Locals; } protected override ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions() { return _scope.LocalFunctions; } internal override bool IsLocalFunctionsScopeBinder { get { return _scope.IsLocalFunctionsScopeBinder; } } protected override ImmutableArray<LabelSymbol> BuildLabels() { return ImmutableArray<LabelSymbol>.Empty; } internal override bool IsLabelsScopeBinder { get { return false; } } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { return _scope.GetDeclaredLocalsForScope(scopeDesignator); } internal override SyntaxNode? ScopeDesignator { get { return _scope.ScopeDesignator; } } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { return _scope.GetDeclaredLocalFunctionsForScope(scopeDesignator); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This binder provides a context for binding within a specific compilation unit, but outside of top-level statements. /// It ensures that locals are in scope, however it is not responsible /// for creating the symbols. That task is actually owned by <see cref="SimpleProgramBinder"/> and /// this binder simply delegates to it when appropriate. That ensures that the same set of symbols is /// shared across all compilation units. /// </summary> internal sealed class SimpleProgramUnitBinder : LocalScopeBinder { private readonly SimpleProgramBinder _scope; public SimpleProgramUnitBinder(Binder enclosing, SimpleProgramBinder scope) : base(enclosing, enclosing.Flags) { _scope = scope; } protected override ImmutableArray<LocalSymbol> BuildLocals() { return _scope.Locals; } protected override ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions() { return _scope.LocalFunctions; } internal override bool IsLocalFunctionsScopeBinder { get { return _scope.IsLocalFunctionsScopeBinder; } } protected override ImmutableArray<LabelSymbol> BuildLabels() { return ImmutableArray<LabelSymbol>.Empty; } internal override bool IsLabelsScopeBinder { get { return false; } } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { return _scope.GetDeclaredLocalsForScope(scopeDesignator); } internal override SyntaxNode? ScopeDesignator { get { return _scope.ScopeDesignator; } } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { return _scope.GetDeclaredLocalFunctionsForScope(scopeDesignator); } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/EditorFeatures/Test/Structure/BlockStructureServiceTests.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Structure { [UseExportProvider] public class BlockStructureServiceTests { [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestSimpleLambda() { var code = @"using System.Linq; class C { static void Goo() { var q = Enumerable.Range(1, 100).Where(x => { return x % 2 == 0; }); } } "; using var workspace = TestWorkspace.CreateCSharp(code); var spans = await GetSpansFromWorkspaceAsync(workspace); // ensure all 4 outlining region tags were found (usings, class, method, lambda) Assert.Equal(4, spans.Length); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestParenthesizedLambda() { var code = @"using System.Linq; class C { static void Goo() { var q = Enumerable.Range(1, 100).Where((x) => { return x % 2 == 0; }); } } "; using var workspace = TestWorkspace.CreateCSharp(code); var spans = await GetSpansFromWorkspaceAsync(workspace); // ensure all 4 outlining region tags were found (usings, class, method, lambda) Assert.Equal(4, spans.Length); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestAnonymousDelegate() { var code = @"using System.Linq; class C { static void Goo() { var q = Enumerable.Range(1, 100).Where(delegate (int x) { return x % 2 == 0; }); } } "; using var workspace = TestWorkspace.CreateCSharp(code); var spans = await GetSpansFromWorkspaceAsync(workspace); // ensure all 4 outlining region tags were found (usings, class, method, anonymous delegate) Assert.Equal(4, spans.Length); } private static async Task<ImmutableArray<BlockSpan>> GetSpansFromWorkspaceAsync( TestWorkspace workspace) { var hostDocument = workspace.Documents.First(); var document = workspace.CurrentSolution.GetDocument(hostDocument.Id); var outliningService = document.GetLanguageService<BlockStructureService>(); var structure = await outliningService.GetBlockStructureAsync(document, CancellationToken.None); return structure.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.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Structure { [UseExportProvider] public class BlockStructureServiceTests { [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestSimpleLambda() { var code = @"using System.Linq; class C { static void Goo() { var q = Enumerable.Range(1, 100).Where(x => { return x % 2 == 0; }); } } "; using var workspace = TestWorkspace.CreateCSharp(code); var spans = await GetSpansFromWorkspaceAsync(workspace); // ensure all 4 outlining region tags were found (usings, class, method, lambda) Assert.Equal(4, spans.Length); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestParenthesizedLambda() { var code = @"using System.Linq; class C { static void Goo() { var q = Enumerable.Range(1, 100).Where((x) => { return x % 2 == 0; }); } } "; using var workspace = TestWorkspace.CreateCSharp(code); var spans = await GetSpansFromWorkspaceAsync(workspace); // ensure all 4 outlining region tags were found (usings, class, method, lambda) Assert.Equal(4, spans.Length); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestAnonymousDelegate() { var code = @"using System.Linq; class C { static void Goo() { var q = Enumerable.Range(1, 100).Where(delegate (int x) { return x % 2 == 0; }); } } "; using var workspace = TestWorkspace.CreateCSharp(code); var spans = await GetSpansFromWorkspaceAsync(workspace); // ensure all 4 outlining region tags were found (usings, class, method, anonymous delegate) Assert.Equal(4, spans.Length); } private static async Task<ImmutableArray<BlockSpan>> GetSpansFromWorkspaceAsync( TestWorkspace workspace) { var hostDocument = workspace.Documents.First(); var document = workspace.CurrentSolution.GetDocument(hostDocument.Id); var outliningService = document.GetLanguageService<BlockStructureService>(); var structure = await outliningService.GetBlockStructureAsync(document, CancellationToken.None); return structure.Spans; } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Compilers/Core/Portable/Operations/Operation.Enumerable.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.Collections; using System; using System.Diagnostics; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal abstract partial class Operation : IOperation { /// <summary> /// Implements a struct-based enumerable for <see cref="Operation"/> nodes, using a slot-based system that tracks /// the current slot, and the current index in the slot if the current slot is an immutable array. This type is not hardened /// to <code>default(Enumerable)</code>, and will null reference in these cases. /// </summary> [NonDefaultable] internal readonly struct Enumerable : IEnumerable<IOperation> { private readonly Operation _operation; internal Enumerable(Operation operation) { _operation = operation; } public Enumerator GetEnumerator() => new Enumerator(_operation); public ImmutableArray<IOperation> ToImmutableArray() { switch (_operation) { case NoneOperation { Children: var children }: return children; case InvalidOperation { Children: var children }: return children; case var _ when !GetEnumerator().MoveNext(): return ImmutableArray<IOperation>.Empty; default: var builder = ArrayBuilder<IOperation>.GetInstance(); foreach (var child in this) { builder.Add(child); } return builder.ToImmutableAndFree(); } } IEnumerator<IOperation> IEnumerable<IOperation>.GetEnumerator() => this.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); } /// <summary> /// Implements a struct-based enumerator for <see cref="Operation"/> nodes, using a slot-based system that tracks /// the current slot, and the current index in the slot if the current slot is an immutable array. This type is not hardened /// to <code>default(Enumerator)</code>, and will null reference in these cases. Implementation of the <see cref="Enumerator.MoveNext"/> /// and <see cref="Enumerator.Current"/> members are delegated to the virtual <see cref="Operation.MoveNext(int, int)"/> and /// <see cref="Operation.GetCurrent(int, int)"/> methods, respectively. Calling <see cref="Current"/> after /// <see cref="Enumerator.MoveNext"/> has returned false will throw an <see cref="InvalidOperationException"/>. /// </summary> [NonDefaultable] internal struct Enumerator : IEnumerator<IOperation> { private readonly Operation _operation; private int _currentSlot; private int _currentIndex; public Enumerator(Operation operation) { _operation = operation; _currentSlot = -1; _currentIndex = -1; } public IOperation Current { get { Debug.Assert(_operation != null && _currentSlot >= 0 && _currentIndex >= 0); return _operation.GetCurrent(_currentSlot, _currentIndex); } } public bool MoveNext() { bool result; (result, _currentSlot, _currentIndex) = _operation.MoveNext(_currentSlot, _currentIndex); return result; } void IEnumerator.Reset() { _currentSlot = -1; _currentIndex = -1; } object? IEnumerator.Current => this.Current; void IDisposable.Dispose() { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections; using System; using System.Diagnostics; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal abstract partial class Operation : IOperation { /// <summary> /// Implements a struct-based enumerable for <see cref="Operation"/> nodes, using a slot-based system that tracks /// the current slot, and the current index in the slot if the current slot is an immutable array. This type is not hardened /// to <code>default(Enumerable)</code>, and will null reference in these cases. /// </summary> [NonDefaultable] internal readonly struct Enumerable : IEnumerable<IOperation> { private readonly Operation _operation; internal Enumerable(Operation operation) { _operation = operation; } public Enumerator GetEnumerator() => new Enumerator(_operation); public ImmutableArray<IOperation> ToImmutableArray() { switch (_operation) { case NoneOperation { Children: var children }: return children; case InvalidOperation { Children: var children }: return children; case var _ when !GetEnumerator().MoveNext(): return ImmutableArray<IOperation>.Empty; default: var builder = ArrayBuilder<IOperation>.GetInstance(); foreach (var child in this) { builder.Add(child); } return builder.ToImmutableAndFree(); } } IEnumerator<IOperation> IEnumerable<IOperation>.GetEnumerator() => this.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); } /// <summary> /// Implements a struct-based enumerator for <see cref="Operation"/> nodes, using a slot-based system that tracks /// the current slot, and the current index in the slot if the current slot is an immutable array. This type is not hardened /// to <code>default(Enumerator)</code>, and will null reference in these cases. Implementation of the <see cref="Enumerator.MoveNext"/> /// and <see cref="Enumerator.Current"/> members are delegated to the virtual <see cref="Operation.MoveNext(int, int)"/> and /// <see cref="Operation.GetCurrent(int, int)"/> methods, respectively. Calling <see cref="Current"/> after /// <see cref="Enumerator.MoveNext"/> has returned false will throw an <see cref="InvalidOperationException"/>. /// </summary> [NonDefaultable] internal struct Enumerator : IEnumerator<IOperation> { private readonly Operation _operation; private int _currentSlot; private int _currentIndex; public Enumerator(Operation operation) { _operation = operation; _currentSlot = -1; _currentIndex = -1; } public IOperation Current { get { Debug.Assert(_operation != null && _currentSlot >= 0 && _currentIndex >= 0); return _operation.GetCurrent(_currentSlot, _currentIndex); } } public bool MoveNext() { bool result; (result, _currentSlot, _currentIndex) = _operation.MoveNext(_currentSlot, _currentIndex); return result; } void IEnumerator.Reset() { _currentSlot = -1; _currentIndex = -1; } object? IEnumerator.Current => this.Current; void IDisposable.Dispose() { } } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Tools/ExternalAccess/FSharp/Editor/IFSharpNavigationBarItemService.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.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor { internal interface IFSharpNavigationBarItemService { Task<IList<FSharpNavigationBarItem>> GetItemsAsync(Document document, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor { internal interface IFSharpNavigationBarItemService { Task<IList<FSharpNavigationBarItem>> GetItemsAsync(Document document, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Compilers/Core/CodeAnalysisTest/CorLibTypesTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class CorLibTypesAndConstantTests : TestBase { [Fact] public void IntegrityTest() { for (int i = 1; i <= (int)SpecialType.Count; i++) { string name = SpecialTypes.GetMetadataName((SpecialType)i); Assert.Equal((SpecialType)i, SpecialTypes.GetTypeFromMetadataName(name)); } for (int i = 0; i <= (int)SpecialType.Count; i++) { Cci.PrimitiveTypeCode code = SpecialTypes.GetTypeCode((SpecialType)i); if (code != Cci.PrimitiveTypeCode.NotPrimitive) { Assert.Equal((SpecialType)i, SpecialTypes.GetTypeFromMetadataName(code)); } } for (int i = 0; i <= (int)Cci.PrimitiveTypeCode.Invalid; i++) { SpecialType id = SpecialTypes.GetTypeFromMetadataName((Cci.PrimitiveTypeCode)i); if (id != SpecialType.None) { Assert.Equal((Cci.PrimitiveTypeCode)i, SpecialTypes.GetTypeCode(id)); } } Assert.Equal(SpecialType.System_Boolean, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Boolean)); Assert.Equal(SpecialType.System_Char, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Char)); Assert.Equal(SpecialType.System_Void, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Void)); Assert.Equal(SpecialType.System_String, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.String)); Assert.Equal(SpecialType.System_Int64, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Int64)); Assert.Equal(SpecialType.System_Int32, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Int32)); Assert.Equal(SpecialType.System_Int16, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Int16)); Assert.Equal(SpecialType.System_SByte, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Int8)); Assert.Equal(SpecialType.System_UInt64, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.UInt64)); Assert.Equal(SpecialType.System_UInt32, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.UInt32)); Assert.Equal(SpecialType.System_UInt16, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.UInt16)); Assert.Equal(SpecialType.System_Byte, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.UInt8)); Assert.Equal(SpecialType.System_Single, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Float32)); Assert.Equal(SpecialType.System_Double, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Float64)); Assert.Equal(SpecialType.System_IntPtr, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.IntPtr)); Assert.Equal(SpecialType.System_UIntPtr, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.UIntPtr)); } [Fact] public void SpecialTypeIsValueType() { var comp = CSharp.CSharpCompilation.Create( "c", options: new CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel), references: new[] { TestMetadata.NetCoreApp.SystemRuntime }); var knownMissingTypes = new HashSet<SpecialType>() { }; for (var specialType = SpecialType.None + 1; specialType <= SpecialType.Count; specialType++) { var symbol = comp.GetSpecialType(specialType); if (knownMissingTypes.Contains(specialType)) { Assert.Equal(SymbolKind.ErrorType, symbol.Kind); } else { Assert.NotEqual(SymbolKind.ErrorType, symbol.Kind); Assert.Equal(symbol.IsValueType, specialType.IsValueType()); } } } [Fact] public void ConstantValueInvalidOperationTest01() { Assert.Throws<InvalidOperationException>(() => { ConstantValue.Create(null, ConstantValueTypeDiscriminator.Bad); }); var cv = ConstantValue.Create(1); Assert.Throws<InvalidOperationException>(() => { var c = cv.StringValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv.CharValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv.DateTimeValue; }); var cv1 = ConstantValue.Create(null, ConstantValueTypeDiscriminator.Null); Assert.Throws<InvalidOperationException>(() => { var c = cv1.BooleanValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv1.DecimalValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv1.DoubleValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv1.SingleValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv1.SByteValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv1.ByteValue; }); } [Fact] public void ConstantValuePropertiesTest01() { Assert.Equal(ConstantValue.Bad, ConstantValue.Default(ConstantValueTypeDiscriminator.Bad)); var cv1 = ConstantValue.Create((sbyte)-1); Assert.True(cv1.IsNegativeNumeric); var cv2 = ConstantValue.Create(-0.12345f); Assert.True(cv2.IsNegativeNumeric); var cv3 = ConstantValue.Create((double)-1.234); Assert.True(cv3.IsNegativeNumeric); var cv4 = ConstantValue.Create((decimal)-12345m); Assert.True(cv4.IsNegativeNumeric); Assert.False(cv4.IsDateTime); var cv5 = ConstantValue.Create(null); Assert.False(cv5.IsNumeric); Assert.False(cv5.IsBoolean); Assert.False(cv5.IsFloating); } [Fact] public void ConstantValueGetHashCodeTest01() { var cv11 = ConstantValue.Create((sbyte)-1); var cv12 = ConstantValue.Create((sbyte)-1); Assert.Equal(cv11.GetHashCode(), cv12.GetHashCode()); var cv21 = ConstantValue.Create((byte)255); var cv22 = ConstantValue.Create((byte)255); Assert.Equal(cv21.GetHashCode(), cv22.GetHashCode()); var cv31 = ConstantValue.Create((short)-32768); var cv32 = ConstantValue.Create((short)-32768); Assert.Equal(cv31.GetHashCode(), cv32.GetHashCode()); var cv41 = ConstantValue.Create((ushort)65535); var cv42 = ConstantValue.Create((ushort)65535); Assert.Equal(cv41.GetHashCode(), cv42.GetHashCode()); // int var cv51 = ConstantValue.Create(12345); var cv52 = ConstantValue.Create(12345); Assert.Equal(cv51.GetHashCode(), cv52.GetHashCode()); var cv61 = ConstantValue.Create(uint.MinValue); var cv62 = ConstantValue.Create(uint.MinValue); Assert.Equal(cv61.GetHashCode(), cv62.GetHashCode()); var cv71 = ConstantValue.Create(long.MaxValue); var cv72 = ConstantValue.Create(long.MaxValue); Assert.Equal(cv71.GetHashCode(), cv72.GetHashCode()); var cv81 = ConstantValue.Create((ulong)123456789); var cv82 = ConstantValue.Create((ulong)123456789); Assert.Equal(cv81.GetHashCode(), cv82.GetHashCode()); var cv91 = ConstantValue.Create(1.1m); var cv92 = ConstantValue.Create(1.1m); Assert.Equal(cv91.GetHashCode(), cv92.GetHashCode()); } // In general, different values are not required to have different hash codes. // But for perf reasons we want hash functions with a good distribution, // so we expect hash codes to differ if a single component is incremented. // But program correctness should be preserved even with a null hash function, // so we need a way to disable these tests during such correctness validation. #if !DISABLE_GOOD_HASH_TESTS [Fact] public void ConstantValueGetHashCodeTest02() { var cv1 = ConstantValue.Create("1"); var cv2 = ConstantValue.Create("2"); Assert.NotEqual(cv1.GetHashCode(), cv2.GetHashCode()); } #endif [Fact] public void ConstantValueToStringTest01() { var cv = ConstantValue.Create(null, ConstantValueTypeDiscriminator.Null); Assert.Equal("ConstantValueNull(null: Null)", cv.ToString()); cv = ConstantValue.Create(null, ConstantValueTypeDiscriminator.String); Assert.Equal("ConstantValueNull(null: Null)", cv.ToString()); // Never hit "ConstantValueString(null: Null)" var strVal = "QC"; cv = ConstantValue.Create(strVal); Assert.Equal(@"ConstantValueString(""QC"": String)", cv.ToString()); cv = ConstantValue.Create((sbyte)-128); Assert.Equal("ConstantValueI8(-128: SByte)", cv.ToString()); cv = ConstantValue.Create((ulong)123456789); Assert.Equal("ConstantValueI64(123456789: UInt64)", cv.ToString()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class CorLibTypesAndConstantTests : TestBase { [Fact] public void IntegrityTest() { for (int i = 1; i <= (int)SpecialType.Count; i++) { string name = SpecialTypes.GetMetadataName((SpecialType)i); Assert.Equal((SpecialType)i, SpecialTypes.GetTypeFromMetadataName(name)); } for (int i = 0; i <= (int)SpecialType.Count; i++) { Cci.PrimitiveTypeCode code = SpecialTypes.GetTypeCode((SpecialType)i); if (code != Cci.PrimitiveTypeCode.NotPrimitive) { Assert.Equal((SpecialType)i, SpecialTypes.GetTypeFromMetadataName(code)); } } for (int i = 0; i <= (int)Cci.PrimitiveTypeCode.Invalid; i++) { SpecialType id = SpecialTypes.GetTypeFromMetadataName((Cci.PrimitiveTypeCode)i); if (id != SpecialType.None) { Assert.Equal((Cci.PrimitiveTypeCode)i, SpecialTypes.GetTypeCode(id)); } } Assert.Equal(SpecialType.System_Boolean, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Boolean)); Assert.Equal(SpecialType.System_Char, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Char)); Assert.Equal(SpecialType.System_Void, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Void)); Assert.Equal(SpecialType.System_String, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.String)); Assert.Equal(SpecialType.System_Int64, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Int64)); Assert.Equal(SpecialType.System_Int32, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Int32)); Assert.Equal(SpecialType.System_Int16, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Int16)); Assert.Equal(SpecialType.System_SByte, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Int8)); Assert.Equal(SpecialType.System_UInt64, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.UInt64)); Assert.Equal(SpecialType.System_UInt32, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.UInt32)); Assert.Equal(SpecialType.System_UInt16, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.UInt16)); Assert.Equal(SpecialType.System_Byte, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.UInt8)); Assert.Equal(SpecialType.System_Single, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Float32)); Assert.Equal(SpecialType.System_Double, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Float64)); Assert.Equal(SpecialType.System_IntPtr, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.IntPtr)); Assert.Equal(SpecialType.System_UIntPtr, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.UIntPtr)); } [Fact] public void SpecialTypeIsValueType() { var comp = CSharp.CSharpCompilation.Create( "c", options: new CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel), references: new[] { TestMetadata.NetCoreApp.SystemRuntime }); var knownMissingTypes = new HashSet<SpecialType>() { }; for (var specialType = SpecialType.None + 1; specialType <= SpecialType.Count; specialType++) { var symbol = comp.GetSpecialType(specialType); if (knownMissingTypes.Contains(specialType)) { Assert.Equal(SymbolKind.ErrorType, symbol.Kind); } else { Assert.NotEqual(SymbolKind.ErrorType, symbol.Kind); Assert.Equal(symbol.IsValueType, specialType.IsValueType()); } } } [Fact] public void ConstantValueInvalidOperationTest01() { Assert.Throws<InvalidOperationException>(() => { ConstantValue.Create(null, ConstantValueTypeDiscriminator.Bad); }); var cv = ConstantValue.Create(1); Assert.Throws<InvalidOperationException>(() => { var c = cv.StringValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv.CharValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv.DateTimeValue; }); var cv1 = ConstantValue.Create(null, ConstantValueTypeDiscriminator.Null); Assert.Throws<InvalidOperationException>(() => { var c = cv1.BooleanValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv1.DecimalValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv1.DoubleValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv1.SingleValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv1.SByteValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv1.ByteValue; }); } [Fact] public void ConstantValuePropertiesTest01() { Assert.Equal(ConstantValue.Bad, ConstantValue.Default(ConstantValueTypeDiscriminator.Bad)); var cv1 = ConstantValue.Create((sbyte)-1); Assert.True(cv1.IsNegativeNumeric); var cv2 = ConstantValue.Create(-0.12345f); Assert.True(cv2.IsNegativeNumeric); var cv3 = ConstantValue.Create((double)-1.234); Assert.True(cv3.IsNegativeNumeric); var cv4 = ConstantValue.Create((decimal)-12345m); Assert.True(cv4.IsNegativeNumeric); Assert.False(cv4.IsDateTime); var cv5 = ConstantValue.Create(null); Assert.False(cv5.IsNumeric); Assert.False(cv5.IsBoolean); Assert.False(cv5.IsFloating); } [Fact] public void ConstantValueGetHashCodeTest01() { var cv11 = ConstantValue.Create((sbyte)-1); var cv12 = ConstantValue.Create((sbyte)-1); Assert.Equal(cv11.GetHashCode(), cv12.GetHashCode()); var cv21 = ConstantValue.Create((byte)255); var cv22 = ConstantValue.Create((byte)255); Assert.Equal(cv21.GetHashCode(), cv22.GetHashCode()); var cv31 = ConstantValue.Create((short)-32768); var cv32 = ConstantValue.Create((short)-32768); Assert.Equal(cv31.GetHashCode(), cv32.GetHashCode()); var cv41 = ConstantValue.Create((ushort)65535); var cv42 = ConstantValue.Create((ushort)65535); Assert.Equal(cv41.GetHashCode(), cv42.GetHashCode()); // int var cv51 = ConstantValue.Create(12345); var cv52 = ConstantValue.Create(12345); Assert.Equal(cv51.GetHashCode(), cv52.GetHashCode()); var cv61 = ConstantValue.Create(uint.MinValue); var cv62 = ConstantValue.Create(uint.MinValue); Assert.Equal(cv61.GetHashCode(), cv62.GetHashCode()); var cv71 = ConstantValue.Create(long.MaxValue); var cv72 = ConstantValue.Create(long.MaxValue); Assert.Equal(cv71.GetHashCode(), cv72.GetHashCode()); var cv81 = ConstantValue.Create((ulong)123456789); var cv82 = ConstantValue.Create((ulong)123456789); Assert.Equal(cv81.GetHashCode(), cv82.GetHashCode()); var cv91 = ConstantValue.Create(1.1m); var cv92 = ConstantValue.Create(1.1m); Assert.Equal(cv91.GetHashCode(), cv92.GetHashCode()); } // In general, different values are not required to have different hash codes. // But for perf reasons we want hash functions with a good distribution, // so we expect hash codes to differ if a single component is incremented. // But program correctness should be preserved even with a null hash function, // so we need a way to disable these tests during such correctness validation. #if !DISABLE_GOOD_HASH_TESTS [Fact] public void ConstantValueGetHashCodeTest02() { var cv1 = ConstantValue.Create("1"); var cv2 = ConstantValue.Create("2"); Assert.NotEqual(cv1.GetHashCode(), cv2.GetHashCode()); } #endif [Fact] public void ConstantValueToStringTest01() { var cv = ConstantValue.Create(null, ConstantValueTypeDiscriminator.Null); Assert.Equal("ConstantValueNull(null: Null)", cv.ToString()); cv = ConstantValue.Create(null, ConstantValueTypeDiscriminator.String); Assert.Equal("ConstantValueNull(null: Null)", cv.ToString()); // Never hit "ConstantValueString(null: Null)" var strVal = "QC"; cv = ConstantValue.Create(strVal); Assert.Equal(@"ConstantValueString(""QC"": String)", cv.ToString()); cv = ConstantValue.Create((sbyte)-128); Assert.Equal("ConstantValueI8(-128: SByte)", cv.ToString()); cv = ConstantValue.Create((ulong)123456789); Assert.Equal("ConstantValueI64(123456789: UInt64)", cv.ToString()); } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Compilers/CSharp/Portable/Emitter/Model/PEAssemblyBuilder.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.Reflection; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal abstract class PEAssemblyBuilderBase : PEModuleBuilder, Cci.IAssemblyReference { private readonly SourceAssemblySymbol _sourceAssembly; /// <summary> /// Additional types injected by the Expression Evaluator. /// </summary> private readonly ImmutableArray<NamedTypeSymbol> _additionalTypes; private ImmutableArray<Cci.IFileReference> _lazyFiles; /// <summary>This is a cache of a subset of <seealso cref="_lazyFiles"/>. We don't include manifest resources in ref assemblies</summary> private ImmutableArray<Cci.IFileReference> _lazyFilesWithoutManifestResources; private SynthesizedEmbeddedAttributeSymbol _lazyEmbeddedAttribute; private SynthesizedEmbeddedAttributeSymbol _lazyIsReadOnlyAttribute; private SynthesizedEmbeddedAttributeSymbol _lazyIsByRefLikeAttribute; private SynthesizedEmbeddedAttributeSymbol _lazyIsUnmanagedAttribute; private SynthesizedEmbeddedNullableAttributeSymbol _lazyNullableAttribute; private SynthesizedEmbeddedNullableContextAttributeSymbol _lazyNullableContextAttribute; private SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol _lazyNullablePublicOnlyAttribute; private SynthesizedEmbeddedNativeIntegerAttributeSymbol _lazyNativeIntegerAttribute; /// <summary> /// The behavior of the C# command-line compiler is as follows: /// 1) If the /out switch is specified, then the explicit assembly name is used. /// 2) Otherwise, /// a) if the assembly is executable, then the assembly name is derived from /// the name of the file containing the entrypoint; /// b) otherwise, the assembly name is derived from the name of the first input /// file. /// /// Since we don't know which method is the entrypoint until well after the /// SourceAssemblySymbol is created, in case 2a, its name will not reflect the /// name of the file containing the entrypoint. We leave it to our caller to /// provide that name explicitly. /// </summary> /// <remarks> /// In cases 1 and 2b, we expect (metadataName == sourceAssembly.MetadataName). /// </remarks> private readonly string _metadataName; public PEAssemblyBuilderBase( SourceAssemblySymbol sourceAssembly, EmitOptions emitOptions, OutputKind outputKind, Cci.ModulePropertiesForSerialization serializationProperties, IEnumerable<ResourceDescription> manifestResources, ImmutableArray<NamedTypeSymbol> additionalTypes) : base((SourceModuleSymbol)sourceAssembly.Modules[0], emitOptions, outputKind, serializationProperties, manifestResources) { Debug.Assert(sourceAssembly is object); _sourceAssembly = sourceAssembly; _additionalTypes = additionalTypes.NullToEmpty(); _metadataName = (emitOptions.OutputNameOverride == null) ? sourceAssembly.MetadataName : FileNameUtilities.ChangeExtension(emitOptions.OutputNameOverride, extension: null); AssemblyOrModuleSymbolToModuleRefMap.Add(sourceAssembly, this); } public sealed override ISourceAssemblySymbolInternal SourceAssemblyOpt => _sourceAssembly; public sealed override ImmutableArray<NamedTypeSymbol> GetAdditionalTopLevelTypes() => _additionalTypes; internal sealed override ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(BindingDiagnosticBag diagnostics) { var builder = ArrayBuilder<NamedTypeSymbol>.GetInstance(); CreateEmbeddedAttributesIfNeeded(diagnostics); builder.AddIfNotNull(_lazyEmbeddedAttribute); builder.AddIfNotNull(_lazyIsReadOnlyAttribute); builder.AddIfNotNull(_lazyIsUnmanagedAttribute); builder.AddIfNotNull(_lazyIsByRefLikeAttribute); builder.AddIfNotNull(_lazyNullableAttribute); builder.AddIfNotNull(_lazyNullableContextAttribute); builder.AddIfNotNull(_lazyNullablePublicOnlyAttribute); builder.AddIfNotNull(_lazyNativeIntegerAttribute); return builder.ToImmutableAndFree(); } public sealed override IEnumerable<Cci.IFileReference> GetFiles(EmitContext context) { if (!context.IsRefAssembly) { return getFiles(ref _lazyFiles); } return getFiles(ref _lazyFilesWithoutManifestResources); ImmutableArray<Cci.IFileReference> getFiles(ref ImmutableArray<Cci.IFileReference> lazyFiles) { if (lazyFiles.IsDefault) { var builder = ArrayBuilder<Cci.IFileReference>.GetInstance(); try { var modules = _sourceAssembly.Modules; for (int i = 1; i < modules.Length; i++) { builder.Add((Cci.IFileReference)Translate(modules[i], context.Diagnostics)); } if (!context.IsRefAssembly) { // resources are not emitted into ref assemblies foreach (ResourceDescription resource in ManifestResources) { if (!resource.IsEmbedded) { builder.Add(resource); } } } // Dev12 compilers don't report ERR_CryptoHashFailed if there are no files to be hashed. if (ImmutableInterlocked.InterlockedInitialize(ref lazyFiles, builder.ToImmutable()) && lazyFiles.Length > 0) { if (!CryptographicHashProvider.IsSupportedAlgorithm(_sourceAssembly.HashAlgorithm)) { context.Diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_CryptoHashFailed), NoLocation.Singleton)); } } } finally { builder.Free(); } } return lazyFiles; } } protected override void AddEmbeddedResourcesFromAddedModules(ArrayBuilder<Cci.ManagedResource> builder, DiagnosticBag diagnostics) { var modules = _sourceAssembly.Modules; int count = modules.Length; for (int i = 1; i < count; i++) { var file = (Cci.IFileReference)Translate(modules[i], diagnostics); try { foreach (EmbeddedResource resource in ((Symbols.Metadata.PE.PEModuleSymbol)modules[i]).Module.GetEmbeddedResourcesOrThrow()) { builder.Add(new Cci.ManagedResource( resource.Name, (resource.Attributes & ManifestResourceAttributes.Public) != 0, null, file, resource.Offset)); } } catch (BadImageFormatException) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, modules[i]), NoLocation.Singleton); } } } public override string Name => _metadataName; public AssemblyIdentity Identity => _sourceAssembly.Identity; public Version AssemblyVersionPattern => _sourceAssembly.AssemblyVersionPattern; internal override SynthesizedAttributeData SynthesizeEmbeddedAttribute() { // _lazyEmbeddedAttribute should have been created before calling this method. return new SynthesizedAttributeData( _lazyEmbeddedAttribute.Constructors[0], ImmutableArray<TypedConstant>.Empty, ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } internal override SynthesizedAttributeData SynthesizeNullableAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments) { if ((object)_lazyNullableAttribute != null) { var constructorIndex = (member == WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags) ? 1 : 0; return new SynthesizedAttributeData( _lazyNullableAttribute.Constructors[constructorIndex], arguments, ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } return base.SynthesizeNullableAttribute(member, arguments); } internal override SynthesizedAttributeData SynthesizeNullableContextAttribute(ImmutableArray<TypedConstant> arguments) { if ((object)_lazyNullableContextAttribute != null) { return new SynthesizedAttributeData( _lazyNullableContextAttribute.Constructors[0], arguments, ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } return base.SynthesizeNullableContextAttribute(arguments); } internal override SynthesizedAttributeData SynthesizeNullablePublicOnlyAttribute(ImmutableArray<TypedConstant> arguments) { if ((object)_lazyNullablePublicOnlyAttribute != null) { return new SynthesizedAttributeData( _lazyNullablePublicOnlyAttribute.Constructors[0], arguments, ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } return base.SynthesizeNullablePublicOnlyAttribute(arguments); } internal override SynthesizedAttributeData SynthesizeNativeIntegerAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments) { if ((object)_lazyNativeIntegerAttribute != null) { var constructorIndex = (member == WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags) ? 1 : 0; return new SynthesizedAttributeData( _lazyNativeIntegerAttribute.Constructors[constructorIndex], arguments, ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } return base.SynthesizeNativeIntegerAttribute(member, arguments); } protected override SynthesizedAttributeData TrySynthesizeIsReadOnlyAttribute() { if ((object)_lazyIsReadOnlyAttribute != null) { return new SynthesizedAttributeData( _lazyIsReadOnlyAttribute.Constructors[0], ImmutableArray<TypedConstant>.Empty, ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } return base.TrySynthesizeIsReadOnlyAttribute(); } protected override SynthesizedAttributeData TrySynthesizeIsUnmanagedAttribute() { if ((object)_lazyIsUnmanagedAttribute != null) { return new SynthesizedAttributeData( _lazyIsUnmanagedAttribute.Constructors[0], ImmutableArray<TypedConstant>.Empty, ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } return base.TrySynthesizeIsUnmanagedAttribute(); } protected override SynthesizedAttributeData TrySynthesizeIsByRefLikeAttribute() { if ((object)_lazyIsByRefLikeAttribute != null) { return new SynthesizedAttributeData( _lazyIsByRefLikeAttribute.Constructors[0], ImmutableArray<TypedConstant>.Empty, ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } return base.TrySynthesizeIsByRefLikeAttribute(); } private void CreateEmbeddedAttributesIfNeeded(BindingDiagnosticBag diagnostics) { EmbeddableAttributes needsAttributes = GetNeedsGeneratedAttributes(); if (ShouldEmitNullablePublicOnlyAttribute() && Compilation.CheckIfAttributeShouldBeEmbedded(EmbeddableAttributes.NullablePublicOnlyAttribute, diagnostics, Location.None)) { needsAttributes |= EmbeddableAttributes.NullablePublicOnlyAttribute; } else if (needsAttributes == 0) { return; } var createParameterlessEmbeddedAttributeSymbol = new Func<string, NamespaceSymbol, BindingDiagnosticBag, SynthesizedEmbeddedAttributeSymbol>(CreateParameterlessEmbeddedAttributeSymbol); CreateAttributeIfNeeded( ref _lazyEmbeddedAttribute, diagnostics, AttributeDescription.CodeAnalysisEmbeddedAttribute, createParameterlessEmbeddedAttributeSymbol); if ((needsAttributes & EmbeddableAttributes.IsReadOnlyAttribute) != 0) { CreateAttributeIfNeeded( ref _lazyIsReadOnlyAttribute, diagnostics, AttributeDescription.IsReadOnlyAttribute, createParameterlessEmbeddedAttributeSymbol); } if ((needsAttributes & EmbeddableAttributes.IsByRefLikeAttribute) != 0) { CreateAttributeIfNeeded( ref _lazyIsByRefLikeAttribute, diagnostics, AttributeDescription.IsByRefLikeAttribute, createParameterlessEmbeddedAttributeSymbol); } if ((needsAttributes & EmbeddableAttributes.IsUnmanagedAttribute) != 0) { CreateAttributeIfNeeded( ref _lazyIsUnmanagedAttribute, diagnostics, AttributeDescription.IsUnmanagedAttribute, createParameterlessEmbeddedAttributeSymbol); } if ((needsAttributes & EmbeddableAttributes.NullableAttribute) != 0) { CreateAttributeIfNeeded( ref _lazyNullableAttribute, diagnostics, AttributeDescription.NullableAttribute, CreateNullableAttributeSymbol); } if ((needsAttributes & EmbeddableAttributes.NullableContextAttribute) != 0) { CreateAttributeIfNeeded( ref _lazyNullableContextAttribute, diagnostics, AttributeDescription.NullableContextAttribute, CreateNullableContextAttributeSymbol); } if ((needsAttributes & EmbeddableAttributes.NullablePublicOnlyAttribute) != 0) { CreateAttributeIfNeeded( ref _lazyNullablePublicOnlyAttribute, diagnostics, AttributeDescription.NullablePublicOnlyAttribute, CreateNullablePublicOnlyAttributeSymbol); } if ((needsAttributes & EmbeddableAttributes.NativeIntegerAttribute) != 0) { CreateAttributeIfNeeded( ref _lazyNativeIntegerAttribute, diagnostics, AttributeDescription.NativeIntegerAttribute, CreateNativeIntegerAttributeSymbol); } } private SynthesizedEmbeddedAttributeSymbol CreateParameterlessEmbeddedAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics) => new SynthesizedEmbeddedAttributeSymbol( name, containingNamespace, SourceModule, baseType: GetWellKnownType(WellKnownType.System_Attribute, diagnostics)); private SynthesizedEmbeddedNullableAttributeSymbol CreateNullableAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics) => new SynthesizedEmbeddedNullableAttributeSymbol( name, containingNamespace, SourceModule, GetWellKnownType(WellKnownType.System_Attribute, diagnostics), GetSpecialType(SpecialType.System_Byte, diagnostics)); private SynthesizedEmbeddedNullableContextAttributeSymbol CreateNullableContextAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics) => new SynthesizedEmbeddedNullableContextAttributeSymbol( name, containingNamespace, SourceModule, GetWellKnownType(WellKnownType.System_Attribute, diagnostics), GetSpecialType(SpecialType.System_Byte, diagnostics)); private SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol CreateNullablePublicOnlyAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics) => new SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol( name, containingNamespace, SourceModule, GetWellKnownType(WellKnownType.System_Attribute, diagnostics), GetSpecialType(SpecialType.System_Boolean, diagnostics)); private SynthesizedEmbeddedNativeIntegerAttributeSymbol CreateNativeIntegerAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics) => new SynthesizedEmbeddedNativeIntegerAttributeSymbol( name, containingNamespace, SourceModule, GetWellKnownType(WellKnownType.System_Attribute, diagnostics), GetSpecialType(SpecialType.System_Boolean, diagnostics)); private void CreateAttributeIfNeeded<T>( ref T symbol, BindingDiagnosticBag diagnostics, AttributeDescription description, Func<string, NamespaceSymbol, BindingDiagnosticBag, T> factory) where T : SynthesizedEmbeddedAttributeSymbolBase { if (symbol is null) { AddDiagnosticsForExistingAttribute(description, diagnostics); var containingNamespace = GetOrSynthesizeNamespace(description.Namespace); symbol = factory(description.Name, containingNamespace, diagnostics); Debug.Assert(symbol.Constructors.Length == description.Signatures.Length); if (symbol.GetAttributeUsageInfo() != AttributeUsageInfo.Default) { EnsureAttributeUsageAttributeMembersAvailable(diagnostics); } AddSynthesizedDefinition(containingNamespace, symbol); } } private void AddDiagnosticsForExistingAttribute(AttributeDescription description, BindingDiagnosticBag diagnostics) { var attributeMetadataName = MetadataTypeName.FromFullName(description.FullName); var userDefinedAttribute = _sourceAssembly.SourceModule.LookupTopLevelMetadataType(ref attributeMetadataName); Debug.Assert((object)userDefinedAttribute.ContainingModule == _sourceAssembly.SourceModule); if (!(userDefinedAttribute is MissingMetadataTypeSymbol)) { diagnostics.Add(ErrorCode.ERR_TypeReserved, userDefinedAttribute.Locations[0], description.FullName); } } private NamespaceSymbol GetOrSynthesizeNamespace(string namespaceFullName) { var result = SourceModule.GlobalNamespace; foreach (var partName in namespaceFullName.Split('.')) { var subnamespace = (NamespaceSymbol)result.GetMembers(partName).FirstOrDefault(m => m.Kind == SymbolKind.Namespace); if (subnamespace == null) { subnamespace = new SynthesizedNamespaceSymbol(result, partName); AddSynthesizedDefinition(result, subnamespace); } result = subnamespace; } return result; } private NamedTypeSymbol GetWellKnownType(WellKnownType type, BindingDiagnosticBag diagnostics) { var result = _sourceAssembly.DeclaringCompilation.GetWellKnownType(type); Binder.ReportUseSite(result, diagnostics, Location.None); return result; } private NamedTypeSymbol GetSpecialType(SpecialType type, BindingDiagnosticBag diagnostics) { var result = _sourceAssembly.DeclaringCompilation.GetSpecialType(type); Binder.ReportUseSite(result, diagnostics, Location.None); return result; } private void EnsureAttributeUsageAttributeMembersAvailable(BindingDiagnosticBag diagnostics) { var compilation = _sourceAssembly.DeclaringCompilation; Binder.GetWellKnownTypeMember(compilation, WellKnownMember.System_AttributeUsageAttribute__ctor, diagnostics, Location.None); Binder.GetWellKnownTypeMember(compilation, WellKnownMember.System_AttributeUsageAttribute__AllowMultiple, diagnostics, Location.None); Binder.GetWellKnownTypeMember(compilation, WellKnownMember.System_AttributeUsageAttribute__Inherited, diagnostics, Location.None); } } #nullable enable internal sealed class PEAssemblyBuilder : PEAssemblyBuilderBase { public PEAssemblyBuilder( SourceAssemblySymbol sourceAssembly, EmitOptions emitOptions, OutputKind outputKind, Cci.ModulePropertiesForSerialization serializationProperties, IEnumerable<ResourceDescription> manifestResources) : base(sourceAssembly, emitOptions, outputKind, serializationProperties, manifestResources, ImmutableArray<NamedTypeSymbol>.Empty) { } public override EmitBaseline? PreviousGeneration => null; public override SymbolChanges? EncSymbolChanges => null; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal abstract class PEAssemblyBuilderBase : PEModuleBuilder, Cci.IAssemblyReference { private readonly SourceAssemblySymbol _sourceAssembly; /// <summary> /// Additional types injected by the Expression Evaluator. /// </summary> private readonly ImmutableArray<NamedTypeSymbol> _additionalTypes; private ImmutableArray<Cci.IFileReference> _lazyFiles; /// <summary>This is a cache of a subset of <seealso cref="_lazyFiles"/>. We don't include manifest resources in ref assemblies</summary> private ImmutableArray<Cci.IFileReference> _lazyFilesWithoutManifestResources; private SynthesizedEmbeddedAttributeSymbol _lazyEmbeddedAttribute; private SynthesizedEmbeddedAttributeSymbol _lazyIsReadOnlyAttribute; private SynthesizedEmbeddedAttributeSymbol _lazyIsByRefLikeAttribute; private SynthesizedEmbeddedAttributeSymbol _lazyIsUnmanagedAttribute; private SynthesizedEmbeddedNullableAttributeSymbol _lazyNullableAttribute; private SynthesizedEmbeddedNullableContextAttributeSymbol _lazyNullableContextAttribute; private SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol _lazyNullablePublicOnlyAttribute; private SynthesizedEmbeddedNativeIntegerAttributeSymbol _lazyNativeIntegerAttribute; /// <summary> /// The behavior of the C# command-line compiler is as follows: /// 1) If the /out switch is specified, then the explicit assembly name is used. /// 2) Otherwise, /// a) if the assembly is executable, then the assembly name is derived from /// the name of the file containing the entrypoint; /// b) otherwise, the assembly name is derived from the name of the first input /// file. /// /// Since we don't know which method is the entrypoint until well after the /// SourceAssemblySymbol is created, in case 2a, its name will not reflect the /// name of the file containing the entrypoint. We leave it to our caller to /// provide that name explicitly. /// </summary> /// <remarks> /// In cases 1 and 2b, we expect (metadataName == sourceAssembly.MetadataName). /// </remarks> private readonly string _metadataName; public PEAssemblyBuilderBase( SourceAssemblySymbol sourceAssembly, EmitOptions emitOptions, OutputKind outputKind, Cci.ModulePropertiesForSerialization serializationProperties, IEnumerable<ResourceDescription> manifestResources, ImmutableArray<NamedTypeSymbol> additionalTypes) : base((SourceModuleSymbol)sourceAssembly.Modules[0], emitOptions, outputKind, serializationProperties, manifestResources) { Debug.Assert(sourceAssembly is object); _sourceAssembly = sourceAssembly; _additionalTypes = additionalTypes.NullToEmpty(); _metadataName = (emitOptions.OutputNameOverride == null) ? sourceAssembly.MetadataName : FileNameUtilities.ChangeExtension(emitOptions.OutputNameOverride, extension: null); AssemblyOrModuleSymbolToModuleRefMap.Add(sourceAssembly, this); } public sealed override ISourceAssemblySymbolInternal SourceAssemblyOpt => _sourceAssembly; public sealed override ImmutableArray<NamedTypeSymbol> GetAdditionalTopLevelTypes() => _additionalTypes; internal sealed override ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(BindingDiagnosticBag diagnostics) { var builder = ArrayBuilder<NamedTypeSymbol>.GetInstance(); CreateEmbeddedAttributesIfNeeded(diagnostics); builder.AddIfNotNull(_lazyEmbeddedAttribute); builder.AddIfNotNull(_lazyIsReadOnlyAttribute); builder.AddIfNotNull(_lazyIsUnmanagedAttribute); builder.AddIfNotNull(_lazyIsByRefLikeAttribute); builder.AddIfNotNull(_lazyNullableAttribute); builder.AddIfNotNull(_lazyNullableContextAttribute); builder.AddIfNotNull(_lazyNullablePublicOnlyAttribute); builder.AddIfNotNull(_lazyNativeIntegerAttribute); return builder.ToImmutableAndFree(); } public sealed override IEnumerable<Cci.IFileReference> GetFiles(EmitContext context) { if (!context.IsRefAssembly) { return getFiles(ref _lazyFiles); } return getFiles(ref _lazyFilesWithoutManifestResources); ImmutableArray<Cci.IFileReference> getFiles(ref ImmutableArray<Cci.IFileReference> lazyFiles) { if (lazyFiles.IsDefault) { var builder = ArrayBuilder<Cci.IFileReference>.GetInstance(); try { var modules = _sourceAssembly.Modules; for (int i = 1; i < modules.Length; i++) { builder.Add((Cci.IFileReference)Translate(modules[i], context.Diagnostics)); } if (!context.IsRefAssembly) { // resources are not emitted into ref assemblies foreach (ResourceDescription resource in ManifestResources) { if (!resource.IsEmbedded) { builder.Add(resource); } } } // Dev12 compilers don't report ERR_CryptoHashFailed if there are no files to be hashed. if (ImmutableInterlocked.InterlockedInitialize(ref lazyFiles, builder.ToImmutable()) && lazyFiles.Length > 0) { if (!CryptographicHashProvider.IsSupportedAlgorithm(_sourceAssembly.HashAlgorithm)) { context.Diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_CryptoHashFailed), NoLocation.Singleton)); } } } finally { builder.Free(); } } return lazyFiles; } } protected override void AddEmbeddedResourcesFromAddedModules(ArrayBuilder<Cci.ManagedResource> builder, DiagnosticBag diagnostics) { var modules = _sourceAssembly.Modules; int count = modules.Length; for (int i = 1; i < count; i++) { var file = (Cci.IFileReference)Translate(modules[i], diagnostics); try { foreach (EmbeddedResource resource in ((Symbols.Metadata.PE.PEModuleSymbol)modules[i]).Module.GetEmbeddedResourcesOrThrow()) { builder.Add(new Cci.ManagedResource( resource.Name, (resource.Attributes & ManifestResourceAttributes.Public) != 0, null, file, resource.Offset)); } } catch (BadImageFormatException) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, modules[i]), NoLocation.Singleton); } } } public override string Name => _metadataName; public AssemblyIdentity Identity => _sourceAssembly.Identity; public Version AssemblyVersionPattern => _sourceAssembly.AssemblyVersionPattern; internal override SynthesizedAttributeData SynthesizeEmbeddedAttribute() { // _lazyEmbeddedAttribute should have been created before calling this method. return new SynthesizedAttributeData( _lazyEmbeddedAttribute.Constructors[0], ImmutableArray<TypedConstant>.Empty, ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } internal override SynthesizedAttributeData SynthesizeNullableAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments) { if ((object)_lazyNullableAttribute != null) { var constructorIndex = (member == WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags) ? 1 : 0; return new SynthesizedAttributeData( _lazyNullableAttribute.Constructors[constructorIndex], arguments, ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } return base.SynthesizeNullableAttribute(member, arguments); } internal override SynthesizedAttributeData SynthesizeNullableContextAttribute(ImmutableArray<TypedConstant> arguments) { if ((object)_lazyNullableContextAttribute != null) { return new SynthesizedAttributeData( _lazyNullableContextAttribute.Constructors[0], arguments, ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } return base.SynthesizeNullableContextAttribute(arguments); } internal override SynthesizedAttributeData SynthesizeNullablePublicOnlyAttribute(ImmutableArray<TypedConstant> arguments) { if ((object)_lazyNullablePublicOnlyAttribute != null) { return new SynthesizedAttributeData( _lazyNullablePublicOnlyAttribute.Constructors[0], arguments, ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } return base.SynthesizeNullablePublicOnlyAttribute(arguments); } internal override SynthesizedAttributeData SynthesizeNativeIntegerAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments) { if ((object)_lazyNativeIntegerAttribute != null) { var constructorIndex = (member == WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags) ? 1 : 0; return new SynthesizedAttributeData( _lazyNativeIntegerAttribute.Constructors[constructorIndex], arguments, ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } return base.SynthesizeNativeIntegerAttribute(member, arguments); } protected override SynthesizedAttributeData TrySynthesizeIsReadOnlyAttribute() { if ((object)_lazyIsReadOnlyAttribute != null) { return new SynthesizedAttributeData( _lazyIsReadOnlyAttribute.Constructors[0], ImmutableArray<TypedConstant>.Empty, ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } return base.TrySynthesizeIsReadOnlyAttribute(); } protected override SynthesizedAttributeData TrySynthesizeIsUnmanagedAttribute() { if ((object)_lazyIsUnmanagedAttribute != null) { return new SynthesizedAttributeData( _lazyIsUnmanagedAttribute.Constructors[0], ImmutableArray<TypedConstant>.Empty, ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } return base.TrySynthesizeIsUnmanagedAttribute(); } protected override SynthesizedAttributeData TrySynthesizeIsByRefLikeAttribute() { if ((object)_lazyIsByRefLikeAttribute != null) { return new SynthesizedAttributeData( _lazyIsByRefLikeAttribute.Constructors[0], ImmutableArray<TypedConstant>.Empty, ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } return base.TrySynthesizeIsByRefLikeAttribute(); } private void CreateEmbeddedAttributesIfNeeded(BindingDiagnosticBag diagnostics) { EmbeddableAttributes needsAttributes = GetNeedsGeneratedAttributes(); if (ShouldEmitNullablePublicOnlyAttribute() && Compilation.CheckIfAttributeShouldBeEmbedded(EmbeddableAttributes.NullablePublicOnlyAttribute, diagnostics, Location.None)) { needsAttributes |= EmbeddableAttributes.NullablePublicOnlyAttribute; } else if (needsAttributes == 0) { return; } var createParameterlessEmbeddedAttributeSymbol = new Func<string, NamespaceSymbol, BindingDiagnosticBag, SynthesizedEmbeddedAttributeSymbol>(CreateParameterlessEmbeddedAttributeSymbol); CreateAttributeIfNeeded( ref _lazyEmbeddedAttribute, diagnostics, AttributeDescription.CodeAnalysisEmbeddedAttribute, createParameterlessEmbeddedAttributeSymbol); if ((needsAttributes & EmbeddableAttributes.IsReadOnlyAttribute) != 0) { CreateAttributeIfNeeded( ref _lazyIsReadOnlyAttribute, diagnostics, AttributeDescription.IsReadOnlyAttribute, createParameterlessEmbeddedAttributeSymbol); } if ((needsAttributes & EmbeddableAttributes.IsByRefLikeAttribute) != 0) { CreateAttributeIfNeeded( ref _lazyIsByRefLikeAttribute, diagnostics, AttributeDescription.IsByRefLikeAttribute, createParameterlessEmbeddedAttributeSymbol); } if ((needsAttributes & EmbeddableAttributes.IsUnmanagedAttribute) != 0) { CreateAttributeIfNeeded( ref _lazyIsUnmanagedAttribute, diagnostics, AttributeDescription.IsUnmanagedAttribute, createParameterlessEmbeddedAttributeSymbol); } if ((needsAttributes & EmbeddableAttributes.NullableAttribute) != 0) { CreateAttributeIfNeeded( ref _lazyNullableAttribute, diagnostics, AttributeDescription.NullableAttribute, CreateNullableAttributeSymbol); } if ((needsAttributes & EmbeddableAttributes.NullableContextAttribute) != 0) { CreateAttributeIfNeeded( ref _lazyNullableContextAttribute, diagnostics, AttributeDescription.NullableContextAttribute, CreateNullableContextAttributeSymbol); } if ((needsAttributes & EmbeddableAttributes.NullablePublicOnlyAttribute) != 0) { CreateAttributeIfNeeded( ref _lazyNullablePublicOnlyAttribute, diagnostics, AttributeDescription.NullablePublicOnlyAttribute, CreateNullablePublicOnlyAttributeSymbol); } if ((needsAttributes & EmbeddableAttributes.NativeIntegerAttribute) != 0) { CreateAttributeIfNeeded( ref _lazyNativeIntegerAttribute, diagnostics, AttributeDescription.NativeIntegerAttribute, CreateNativeIntegerAttributeSymbol); } } private SynthesizedEmbeddedAttributeSymbol CreateParameterlessEmbeddedAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics) => new SynthesizedEmbeddedAttributeSymbol( name, containingNamespace, SourceModule, baseType: GetWellKnownType(WellKnownType.System_Attribute, diagnostics)); private SynthesizedEmbeddedNullableAttributeSymbol CreateNullableAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics) => new SynthesizedEmbeddedNullableAttributeSymbol( name, containingNamespace, SourceModule, GetWellKnownType(WellKnownType.System_Attribute, diagnostics), GetSpecialType(SpecialType.System_Byte, diagnostics)); private SynthesizedEmbeddedNullableContextAttributeSymbol CreateNullableContextAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics) => new SynthesizedEmbeddedNullableContextAttributeSymbol( name, containingNamespace, SourceModule, GetWellKnownType(WellKnownType.System_Attribute, diagnostics), GetSpecialType(SpecialType.System_Byte, diagnostics)); private SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol CreateNullablePublicOnlyAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics) => new SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol( name, containingNamespace, SourceModule, GetWellKnownType(WellKnownType.System_Attribute, diagnostics), GetSpecialType(SpecialType.System_Boolean, diagnostics)); private SynthesizedEmbeddedNativeIntegerAttributeSymbol CreateNativeIntegerAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics) => new SynthesizedEmbeddedNativeIntegerAttributeSymbol( name, containingNamespace, SourceModule, GetWellKnownType(WellKnownType.System_Attribute, diagnostics), GetSpecialType(SpecialType.System_Boolean, diagnostics)); private void CreateAttributeIfNeeded<T>( ref T symbol, BindingDiagnosticBag diagnostics, AttributeDescription description, Func<string, NamespaceSymbol, BindingDiagnosticBag, T> factory) where T : SynthesizedEmbeddedAttributeSymbolBase { if (symbol is null) { AddDiagnosticsForExistingAttribute(description, diagnostics); var containingNamespace = GetOrSynthesizeNamespace(description.Namespace); symbol = factory(description.Name, containingNamespace, diagnostics); Debug.Assert(symbol.Constructors.Length == description.Signatures.Length); if (symbol.GetAttributeUsageInfo() != AttributeUsageInfo.Default) { EnsureAttributeUsageAttributeMembersAvailable(diagnostics); } AddSynthesizedDefinition(containingNamespace, symbol); } } private void AddDiagnosticsForExistingAttribute(AttributeDescription description, BindingDiagnosticBag diagnostics) { var attributeMetadataName = MetadataTypeName.FromFullName(description.FullName); var userDefinedAttribute = _sourceAssembly.SourceModule.LookupTopLevelMetadataType(ref attributeMetadataName); Debug.Assert((object)userDefinedAttribute.ContainingModule == _sourceAssembly.SourceModule); if (!(userDefinedAttribute is MissingMetadataTypeSymbol)) { diagnostics.Add(ErrorCode.ERR_TypeReserved, userDefinedAttribute.Locations[0], description.FullName); } } private NamespaceSymbol GetOrSynthesizeNamespace(string namespaceFullName) { var result = SourceModule.GlobalNamespace; foreach (var partName in namespaceFullName.Split('.')) { var subnamespace = (NamespaceSymbol)result.GetMembers(partName).FirstOrDefault(m => m.Kind == SymbolKind.Namespace); if (subnamespace == null) { subnamespace = new SynthesizedNamespaceSymbol(result, partName); AddSynthesizedDefinition(result, subnamespace); } result = subnamespace; } return result; } private NamedTypeSymbol GetWellKnownType(WellKnownType type, BindingDiagnosticBag diagnostics) { var result = _sourceAssembly.DeclaringCompilation.GetWellKnownType(type); Binder.ReportUseSite(result, diagnostics, Location.None); return result; } private NamedTypeSymbol GetSpecialType(SpecialType type, BindingDiagnosticBag diagnostics) { var result = _sourceAssembly.DeclaringCompilation.GetSpecialType(type); Binder.ReportUseSite(result, diagnostics, Location.None); return result; } private void EnsureAttributeUsageAttributeMembersAvailable(BindingDiagnosticBag diagnostics) { var compilation = _sourceAssembly.DeclaringCompilation; Binder.GetWellKnownTypeMember(compilation, WellKnownMember.System_AttributeUsageAttribute__ctor, diagnostics, Location.None); Binder.GetWellKnownTypeMember(compilation, WellKnownMember.System_AttributeUsageAttribute__AllowMultiple, diagnostics, Location.None); Binder.GetWellKnownTypeMember(compilation, WellKnownMember.System_AttributeUsageAttribute__Inherited, diagnostics, Location.None); } } #nullable enable internal sealed class PEAssemblyBuilder : PEAssemblyBuilderBase { public PEAssemblyBuilder( SourceAssemblySymbol sourceAssembly, EmitOptions emitOptions, OutputKind outputKind, Cci.ModulePropertiesForSerialization serializationProperties, IEnumerable<ResourceDescription> manifestResources) : base(sourceAssembly, emitOptions, outputKind, serializationProperties, manifestResources, ImmutableArray<NamedTypeSymbol>.Empty) { } public override EmitBaseline? PreviousGeneration => null; public override SymbolChanges? EncSymbolChanges => null; } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/EditorFeatures/CSharpTest2/Recommendations/GotoKeywordRecommenderTests.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.Editor.CSharp.UnitTests.Recommendations { public class GotoKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$ return true;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatement() { await VerifyKeywordAsync(AddInsideMethod( @"return true; $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBlock() { await VerifyKeywordAsync(AddInsideMethod( @"if (true) { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGoto() { await VerifyAbsenceAsync(AddInsideMethod( @"goto $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClass() { await VerifyAbsenceAsync( @"class C { $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssignment() { await VerifyKeywordAsync(AddInsideMethod( @" if (b != 0) { count <<= 2; char[] newBuffer = new char[count]; for (int copy = 0; copy < j; copy++) newBuffer[copy] = buffer[copy]; buffer = newBuffer; $$ Restart; }")); } } }
// Licensed to the .NET Foundation under one or more 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.Editor.CSharp.UnitTests.Recommendations { public class GotoKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$ return true;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatement() { await VerifyKeywordAsync(AddInsideMethod( @"return true; $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBlock() { await VerifyKeywordAsync(AddInsideMethod( @"if (true) { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGoto() { await VerifyAbsenceAsync(AddInsideMethod( @"goto $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClass() { await VerifyAbsenceAsync( @"class C { $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssignment() { await VerifyKeywordAsync(AddInsideMethod( @" if (b != 0) { count <<= 2; char[] newBuffer = new char[count]; for (int copy = 0; copy < j; copy++) newBuffer[copy] = buffer[copy]; buffer = newBuffer; $$ Restart; }")); } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/OperatorDeclarationStructureTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure.MetadataAsSource { public class OperatorDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<OperatorDeclarationSyntax> { protected override string WorkspaceKind => CodeAnalysis.WorkspaceKind.MetadataAsSource; internal override AbstractSyntaxStructureProvider CreateProvider() => new OperatorDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task NoCommentsOrAttributes() { const string code = @" class Goo { public static bool operator $$==(Goo a, Goo b); }"; await VerifyNoBlockSpansAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithAttributes() { const string code = @" class Goo { {|hint:{|textspan:[Blah] |}public static bool operator $$==(Goo a, Goo b);|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithCommentsAndAttributes() { const string code = @" class Goo { {|hint:{|textspan:// Summary: // This is a summary. [Blah] |}bool operator $$==(Goo a, Goo b);|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithCommentsAttributesAndModifiers() { const string code = @" class Goo { {|hint:{|textspan:// Summary: // This is a summary. [Blah] |}public static bool operator $$==(Goo a, Goo b);|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestOperator3() { const string code = @" class C { $${|#0:public static int operator +(int i){|textspan: { }|#0} |} public static int operator -(int i) { } }"; await VerifyBlockSpansAsync(code, Region("textspan", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure.MetadataAsSource { public class OperatorDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<OperatorDeclarationSyntax> { protected override string WorkspaceKind => CodeAnalysis.WorkspaceKind.MetadataAsSource; internal override AbstractSyntaxStructureProvider CreateProvider() => new OperatorDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task NoCommentsOrAttributes() { const string code = @" class Goo { public static bool operator $$==(Goo a, Goo b); }"; await VerifyNoBlockSpansAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithAttributes() { const string code = @" class Goo { {|hint:{|textspan:[Blah] |}public static bool operator $$==(Goo a, Goo b);|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithCommentsAndAttributes() { const string code = @" class Goo { {|hint:{|textspan:// Summary: // This is a summary. [Blah] |}bool operator $$==(Goo a, Goo b);|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithCommentsAttributesAndModifiers() { const string code = @" class Goo { {|hint:{|textspan:// Summary: // This is a summary. [Blah] |}public static bool operator $$==(Goo a, Goo b);|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestOperator3() { const string code = @" class C { $${|#0:public static int operator +(int i){|textspan: { }|#0} |} public static int operator -(int i) { } }"; await VerifyBlockSpansAsync(code, Region("textspan", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/UsingsAndExternAliasesDirectiveComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Utilities { internal class UsingsAndExternAliasesDirectiveComparer : IComparer<SyntaxNode?> { public static readonly IComparer<SyntaxNode> NormalInstance = new UsingsAndExternAliasesDirectiveComparer( NameSyntaxComparer.Create(TokenComparer.NormalInstance), TokenComparer.NormalInstance); public static readonly IComparer<SyntaxNode> SystemFirstInstance = new UsingsAndExternAliasesDirectiveComparer( NameSyntaxComparer.Create(TokenComparer.SystemFirstInstance), TokenComparer.SystemFirstInstance); private readonly IComparer<NameSyntax> _nameComparer; private readonly IComparer<SyntaxToken> _tokenComparer; private UsingsAndExternAliasesDirectiveComparer( IComparer<NameSyntax> nameComparer, IComparer<SyntaxToken> tokenComparer) { RoslynDebug.AssertNotNull(nameComparer); RoslynDebug.AssertNotNull(tokenComparer); _nameComparer = nameComparer; _tokenComparer = tokenComparer; } private enum UsingKind { Extern, GlobalNamespace, GlobalUsingStatic, GlobalAlias, Namespace, UsingStatic, Alias } private static UsingKind GetUsingKind(UsingDirectiveSyntax? usingDirective, ExternAliasDirectiveSyntax? externDirective) { if (externDirective != null) { return UsingKind.Extern; } else { RoslynDebug.AssertNotNull(usingDirective); } if (usingDirective.GlobalKeyword != default) { if (usingDirective.Alias != null) return UsingKind.GlobalAlias; if (usingDirective.StaticKeyword != default) return UsingKind.GlobalUsingStatic; return UsingKind.GlobalNamespace; } else { if (usingDirective.Alias != null) return UsingKind.Alias; if (usingDirective.StaticKeyword != default) return UsingKind.UsingStatic; return UsingKind.Namespace; } } public int Compare(SyntaxNode? directive1, SyntaxNode? directive2) { if (directive1 is null) return directive2 is null ? 0 : -1; else if (directive2 is null) return 1; if (directive1 == directive2) return 0; var using1 = directive1 as UsingDirectiveSyntax; var using2 = directive2 as UsingDirectiveSyntax; var extern1 = directive1 as ExternAliasDirectiveSyntax; var extern2 = directive2 as ExternAliasDirectiveSyntax; var directive1Kind = GetUsingKind(using1, extern1); var directive2Kind = GetUsingKind(using2, extern2); // different types of usings get broken up into groups. // * externs // * usings // * using statics // * aliases var directiveKindDifference = directive1Kind - directive2Kind; if (directiveKindDifference != 0) { return directiveKindDifference; } // ok, it's the same type of using now. switch (directive1Kind) { case UsingKind.Extern: // they're externs, sort by the alias return _tokenComparer.Compare(extern1!.Identifier, extern2!.Identifier); case UsingKind.Alias: var aliasComparisonResult = _tokenComparer.Compare(using1!.Alias!.Name.Identifier, using2!.Alias!.Name.Identifier); if (aliasComparisonResult == 0) { // They both use the same alias, so compare the names. return _nameComparer.Compare(using1.Name, using2.Name); } return aliasComparisonResult; default: return _nameComparer.Compare(using1!.Name, using2!.Name); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Utilities { internal class UsingsAndExternAliasesDirectiveComparer : IComparer<SyntaxNode?> { public static readonly IComparer<SyntaxNode> NormalInstance = new UsingsAndExternAliasesDirectiveComparer( NameSyntaxComparer.Create(TokenComparer.NormalInstance), TokenComparer.NormalInstance); public static readonly IComparer<SyntaxNode> SystemFirstInstance = new UsingsAndExternAliasesDirectiveComparer( NameSyntaxComparer.Create(TokenComparer.SystemFirstInstance), TokenComparer.SystemFirstInstance); private readonly IComparer<NameSyntax> _nameComparer; private readonly IComparer<SyntaxToken> _tokenComparer; private UsingsAndExternAliasesDirectiveComparer( IComparer<NameSyntax> nameComparer, IComparer<SyntaxToken> tokenComparer) { RoslynDebug.AssertNotNull(nameComparer); RoslynDebug.AssertNotNull(tokenComparer); _nameComparer = nameComparer; _tokenComparer = tokenComparer; } private enum UsingKind { Extern, GlobalNamespace, GlobalUsingStatic, GlobalAlias, Namespace, UsingStatic, Alias } private static UsingKind GetUsingKind(UsingDirectiveSyntax? usingDirective, ExternAliasDirectiveSyntax? externDirective) { if (externDirective != null) { return UsingKind.Extern; } else { RoslynDebug.AssertNotNull(usingDirective); } if (usingDirective.GlobalKeyword != default) { if (usingDirective.Alias != null) return UsingKind.GlobalAlias; if (usingDirective.StaticKeyword != default) return UsingKind.GlobalUsingStatic; return UsingKind.GlobalNamespace; } else { if (usingDirective.Alias != null) return UsingKind.Alias; if (usingDirective.StaticKeyword != default) return UsingKind.UsingStatic; return UsingKind.Namespace; } } public int Compare(SyntaxNode? directive1, SyntaxNode? directive2) { if (directive1 is null) return directive2 is null ? 0 : -1; else if (directive2 is null) return 1; if (directive1 == directive2) return 0; var using1 = directive1 as UsingDirectiveSyntax; var using2 = directive2 as UsingDirectiveSyntax; var extern1 = directive1 as ExternAliasDirectiveSyntax; var extern2 = directive2 as ExternAliasDirectiveSyntax; var directive1Kind = GetUsingKind(using1, extern1); var directive2Kind = GetUsingKind(using2, extern2); // different types of usings get broken up into groups. // * externs // * usings // * using statics // * aliases var directiveKindDifference = directive1Kind - directive2Kind; if (directiveKindDifference != 0) { return directiveKindDifference; } // ok, it's the same type of using now. switch (directive1Kind) { case UsingKind.Extern: // they're externs, sort by the alias return _tokenComparer.Compare(extern1!.Identifier, extern2!.Identifier); case UsingKind.Alias: var aliasComparisonResult = _tokenComparer.Compare(using1!.Alias!.Name.Identifier, using2!.Alias!.Name.Identifier); if (aliasComparisonResult == 0) { // They both use the same alias, so compare the names. return _nameComparer.Compare(using1.Name, using2.Name); } return aliasComparisonResult; default: return _nameComparer.Compare(using1!.Name, using2!.Name); } } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/EditorFeatures/Core.Wpf/QuickInfo/IContentControlService.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.Windows; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.QuickInfo { internal interface IContentControlService : IWorkspaceService { /// <summary> /// return <see cref="ViewHostingControl"/> from the given <paramref name="textBuffer"/>'s <paramref name="contentSpan"/> /// </summary> ViewHostingControl CreateViewHostingControl(ITextBuffer textBuffer, Span contentSpan); /// <summary> /// get <see cref="DisposableToolTip"/> /> from the given <paramref name="textBuffer"/>'s <paramref name="contentSpan"/> /// based on given <paramref name="baseDocument"/> /// /// tooltip will show embedded textview which shows code from the content span of the text buffer with the context of the /// base document /// </summary> /// <param name="baseDocument">document to be used as a context for the code</param> /// <param name="textBuffer">buffer to show in the tooltip text view</param> /// <param name="contentSpan">actual span to show in the tooptip</param> /// <param name="backgroundResourceKey">background of the tooltip control</param> /// <returns>ToolTip control with dispose method</returns> DisposableToolTip CreateDisposableToolTip(Document baseDocument, ITextBuffer textBuffer, Span contentSpan, object backgroundResourceKey); /// <summary> /// get <see cref="DisposableToolTip"/> /> from the given <paramref name="textBuffer"/> /// /// tooltip will show embedded textview with whole content from the buffer. if the buffer has associated tags /// in its property bag, it will be picked up by taggers associated with the tooltip /// </summary> DisposableToolTip CreateDisposableToolTip(ITextBuffer textBuffer, object backgroundResourceKey); /// <summary> /// attach <see cref="DisposableToolTip"/> to the given <paramref name="element"/> /// /// this will lazily create the tooltip and dispose it properly when it goes away /// </summary> void AttachToolTipToControl(FrameworkElement element, Func<DisposableToolTip> createToolTip); } }
// Licensed to the .NET Foundation under one or more 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.Windows; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.QuickInfo { internal interface IContentControlService : IWorkspaceService { /// <summary> /// return <see cref="ViewHostingControl"/> from the given <paramref name="textBuffer"/>'s <paramref name="contentSpan"/> /// </summary> ViewHostingControl CreateViewHostingControl(ITextBuffer textBuffer, Span contentSpan); /// <summary> /// get <see cref="DisposableToolTip"/> /> from the given <paramref name="textBuffer"/>'s <paramref name="contentSpan"/> /// based on given <paramref name="baseDocument"/> /// /// tooltip will show embedded textview which shows code from the content span of the text buffer with the context of the /// base document /// </summary> /// <param name="baseDocument">document to be used as a context for the code</param> /// <param name="textBuffer">buffer to show in the tooltip text view</param> /// <param name="contentSpan">actual span to show in the tooptip</param> /// <param name="backgroundResourceKey">background of the tooltip control</param> /// <returns>ToolTip control with dispose method</returns> DisposableToolTip CreateDisposableToolTip(Document baseDocument, ITextBuffer textBuffer, Span contentSpan, object backgroundResourceKey); /// <summary> /// get <see cref="DisposableToolTip"/> /> from the given <paramref name="textBuffer"/> /// /// tooltip will show embedded textview with whole content from the buffer. if the buffer has associated tags /// in its property bag, it will be picked up by taggers associated with the tooltip /// </summary> DisposableToolTip CreateDisposableToolTip(ITextBuffer textBuffer, object backgroundResourceKey); /// <summary> /// attach <see cref="DisposableToolTip"/> to the given <paramref name="element"/> /// /// this will lazily create the tooltip and dispose it properly when it goes away /// </summary> void AttachToolTipToControl(FrameworkElement element, Func<DisposableToolTip> createToolTip); } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/MarginGlyph/TargetMenuItemViewModel.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.Editor.Wpf; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.InheritanceMargin; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { /// <summary> /// View model used to show the MenuItem for inheritance target. /// </summary> internal class TargetMenuItemViewModel : InheritanceMenuItemViewModel { /// <summary> /// DefinitionItem used for navigation. /// </summary> public DefinitionItem DefinitionItem { get; } // Internal for testing purpose internal TargetMenuItemViewModel( string displayContent, ImageMoniker imageMoniker, string automationName, DefinitionItem definitionItem) : base(displayContent, imageMoniker, automationName) { DefinitionItem = definitionItem; } public static TargetMenuItemViewModel Create(InheritanceTargetItem target) { var displayContent = target.DisplayName; var imageMoniker = target.Glyph.GetImageMoniker(); return new TargetMenuItemViewModel( displayContent, imageMoniker, displayContent, target.DefinitionItem); } } }
// Licensed to the .NET Foundation under one or more 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.Editor.Wpf; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.InheritanceMargin; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { /// <summary> /// View model used to show the MenuItem for inheritance target. /// </summary> internal class TargetMenuItemViewModel : InheritanceMenuItemViewModel { /// <summary> /// DefinitionItem used for navigation. /// </summary> public DefinitionItem DefinitionItem { get; } // Internal for testing purpose internal TargetMenuItemViewModel( string displayContent, ImageMoniker imageMoniker, string automationName, DefinitionItem definitionItem) : base(displayContent, imageMoniker, automationName) { DefinitionItem = definitionItem; } public static TargetMenuItemViewModel Create(InheritanceTargetItem target) { var displayContent = target.DisplayName; var imageMoniker = target.Glyph.GetImageMoniker(); return new TargetMenuItemViewModel( displayContent, imageMoniker, displayContent, target.DefinitionItem); } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForConversionOperatorsAnalyzerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { using VerifyCS = CSharpCodeFixVerifier< UseExpressionBodyDiagnosticAnalyzer, UseExpressionBodyCodeFixProvider>; public class UseExpressionBodyForConversionOperatorsAnalyzerTests { private static async Task TestWithUseExpressionBody(string code, string fixedCode) { await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, ExpressionBodyPreference.WhenPossible } } }.RunAsync(); } private static async Task TestWithUseBlockBody(string code, string fixedCode) { await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, ExpressionBodyPreference.Never } } }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody1() { var code = @" class C { static int Bar() { return 0; } {|IDE0023:public static implicit operator {|CS0161:C|}(int i) { Bar(); }|} }"; var fixedCode = @" class C { static int Bar() { return 0; } public static implicit operator C(int i) => Bar(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody2() { var code = @" class C { static int Bar() { return 0; } {|IDE0023:public static implicit operator C(int i) { return Bar(); }|} }"; var fixedCode = @" class C { static int Bar() { return 0; } public static implicit operator C(int i) => Bar(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody3() { var code = @" using System; class C { {|IDE0023:public static implicit operator C(int i) { throw new NotImplementedException(); }|} }"; var fixedCode = @" using System; class C { public static implicit operator C(int i) => throw new NotImplementedException(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody4() { var code = @" using System; class C { {|IDE0023:public static implicit operator C(int i) { throw new NotImplementedException(); // comment }|} }"; var fixedCode = @" using System; class C { public static implicit operator C(int i) => throw new NotImplementedException(); // comment }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody1() { var code = @" class C { static int Bar() { return 0; } {|IDE0023:public static implicit operator C(int i) => Bar();|} }"; var fixedCode = @" class C { static int Bar() { return 0; } public static implicit operator C(int i) { return Bar(); } }"; await TestWithUseBlockBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody3() { var code = @" using System; class C { {|IDE0023:public static implicit operator C(int i) => throw new NotImplementedException();|} }"; var fixedCode = @" using System; class C { public static implicit operator C(int i) { throw new NotImplementedException(); } }"; await TestWithUseBlockBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody4() { var code = @" using System; class C { {|IDE0023:public static implicit operator C(int i) => throw new NotImplementedException();|} // comment }"; var fixedCode = @" using System; class C { public static implicit operator C(int i) { throw new NotImplementedException(); // comment } }"; await TestWithUseBlockBody(code, fixedCode); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { using VerifyCS = CSharpCodeFixVerifier< UseExpressionBodyDiagnosticAnalyzer, UseExpressionBodyCodeFixProvider>; public class UseExpressionBodyForConversionOperatorsAnalyzerTests { private static async Task TestWithUseExpressionBody(string code, string fixedCode) { await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, ExpressionBodyPreference.WhenPossible } } }.RunAsync(); } private static async Task TestWithUseBlockBody(string code, string fixedCode) { await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, ExpressionBodyPreference.Never } } }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody1() { var code = @" class C { static int Bar() { return 0; } {|IDE0023:public static implicit operator {|CS0161:C|}(int i) { Bar(); }|} }"; var fixedCode = @" class C { static int Bar() { return 0; } public static implicit operator C(int i) => Bar(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody2() { var code = @" class C { static int Bar() { return 0; } {|IDE0023:public static implicit operator C(int i) { return Bar(); }|} }"; var fixedCode = @" class C { static int Bar() { return 0; } public static implicit operator C(int i) => Bar(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody3() { var code = @" using System; class C { {|IDE0023:public static implicit operator C(int i) { throw new NotImplementedException(); }|} }"; var fixedCode = @" using System; class C { public static implicit operator C(int i) => throw new NotImplementedException(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody4() { var code = @" using System; class C { {|IDE0023:public static implicit operator C(int i) { throw new NotImplementedException(); // comment }|} }"; var fixedCode = @" using System; class C { public static implicit operator C(int i) => throw new NotImplementedException(); // comment }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody1() { var code = @" class C { static int Bar() { return 0; } {|IDE0023:public static implicit operator C(int i) => Bar();|} }"; var fixedCode = @" class C { static int Bar() { return 0; } public static implicit operator C(int i) { return Bar(); } }"; await TestWithUseBlockBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody3() { var code = @" using System; class C { {|IDE0023:public static implicit operator C(int i) => throw new NotImplementedException();|} }"; var fixedCode = @" using System; class C { public static implicit operator C(int i) { throw new NotImplementedException(); } }"; await TestWithUseBlockBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody4() { var code = @" using System; class C { {|IDE0023:public static implicit operator C(int i) => throw new NotImplementedException();|} // comment }"; var fixedCode = @" using System; class C { public static implicit operator C(int i) { throw new NotImplementedException(); // comment } }"; await TestWithUseBlockBody(code, fixedCode); } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/VisualStudio/Core/Def/Implementation/Preview/ReferenceChange.MetadataReferenceChange.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; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview { internal abstract partial class ReferenceChange : AbstractChange { private sealed class MetadataReferenceChange : ReferenceChange { private readonly MetadataReference _reference; public MetadataReferenceChange(MetadataReference reference, ProjectId projectId, string projectName, bool isAdded, PreviewEngine engine) : base(projectId, projectName, isAdded, engine) { _reference = reference; } internal override Solution AddToSolution(Solution solution) => solution.AddMetadataReference(this.ProjectId, _reference); internal override Solution RemoveFromSolution(Solution solution) => solution.RemoveMetadataReference(this.ProjectId, _reference); protected override string GetDisplayText() { var display = _reference.Display ?? ServicesVSResources.Unknown1; return string.Format(ServicesVSResources.Reference_to_0_in_project_1, display, this.ProjectName); } } } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview { internal abstract partial class ReferenceChange : AbstractChange { private sealed class MetadataReferenceChange : ReferenceChange { private readonly MetadataReference _reference; public MetadataReferenceChange(MetadataReference reference, ProjectId projectId, string projectName, bool isAdded, PreviewEngine engine) : base(projectId, projectName, isAdded, engine) { _reference = reference; } internal override Solution AddToSolution(Solution solution) => solution.AddMetadataReference(this.ProjectId, _reference); internal override Solution RemoveFromSolution(Solution solution) => solution.RemoveMetadataReference(this.ProjectId, _reference); protected override string GetDisplayText() { var display = _reference.Display ?? ServicesVSResources.Unknown1; return string.Format(ServicesVSResources.Reference_to_0_in_project_1, display, this.ProjectName); } } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/EditorFeatures/CSharpTest/MakeLocalFunctionStatic/MakeLocalFunctionStaticRefactoringTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.MakeLocalFunctionStatic; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeLocalFunctionStatic { public class MakeLocalFunctionStaticRefactoringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new MakeLocalFunctionStaticCodeRefactoringProvider(); private static readonly ParseOptions CSharp72ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_2); private static readonly ParseOptions CSharp8ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldNotTriggerForCSharp7() { await TestMissingAsync( @"class C { int N(int x) { return AddLocal(); int [||]AddLocal() { return x + 1; } } }", parameters: new TestParameters(parseOptions: CSharp72ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldNotTriggerIfNoCaptures() { await TestMissingAsync( @"class C { int N(int x) { return AddLocal(x); int [||]AddLocal(int x) { return x + 1; } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldNotTriggerIfAlreadyStatic() { await TestMissingAsync( @"class C { int N(int x) { return AddLocal(x); static int [||]AddLocal(int x) { return x + 1; } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldNotTriggerIfAlreadyStaticWithError() { await TestMissingAsync( @"class C { int N(int x) { return AddLocal(); static int [||]AddLocal() { return x + 1; } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldNotTriggerIfCapturesThisParameter() { await TestMissingAsync( @"class C { int x; int N() { return AddLocal(); int [||]AddLocal() { return x + 1; } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldTriggerIfExplicitlyPassedInThisParameter() { await TestInRegularAndScriptAsync( @"class C { int x; int N() { int y; return AddLocal(this); int [||]AddLocal(C c) { return c.x + y; } } }", @"class C { int x; int N() { int y; return AddLocal(this, y); static int [||]AddLocal(C c, int y) { return c.x + y; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldTriggerForCSharp8() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { return AddLocal(); int [||]AddLocal() { return x + 1; } } }", @"class C { int N(int x) { return AddLocal(x); static int AddLocal(int x) { return x + 1; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestMultipleVariables() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; return AddLocal(); int[||] AddLocal() { return x + y; } } }", @"class C { int N(int x) { int y = 10; return AddLocal(x, y); static int AddLocal(int x, int y) { return x + y; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestMultipleCalls() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; return AddLocal() + AddLocal(); int[||] AddLocal() { return x + y; } } }", @"class C { int N(int x) { int y = 10; return AddLocal(x, y) + AddLocal(x, y); static int AddLocal(int x, int y) { return x + y; } } }" , parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestMultipleCallsWithExistingParameters() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; var m = AddLocal(1, 2); return AddLocal(m, m); int[||] AddLocal(int a, int b) { return a + b + x + y; } } }", @"class C { int N(int x) { int y = 10; var m = AddLocal(1, 2, x, y); return AddLocal(m, m, x, y); static int AddLocal(int a, int b, int x, int y) { return a + b + x + y; } } }" , parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestRecursiveCall() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; var m = AddLocal(1, 2); return AddLocal(m, m); int[||] AddLocal(int a, int b) { return AddLocal(a, b) + x + y; } } }", @"class C { int N(int x) { int y = 10; var m = AddLocal(1, 2, x, y); return AddLocal(m, m, x, y); static int AddLocal(int a, int b, int x, int y) { return AddLocal(a, b, x, y) + x + y; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestCallInArgumentList() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; return AddLocal(AddLocal(1, 2), AddLocal(3, 4)); int[||] AddLocal(int a, int b) { return AddLocal(a, b) + x + y; } } }", @"class C { int N(int x) { int y = 10; return AddLocal(AddLocal(1, 2, x, y), AddLocal(3, 4, x, y), x, y); static int AddLocal(int a, int b, int x, int y) { return AddLocal(a, b, x, y) + x + y; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestCallsWithNamedArguments() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; var m = AddLocal(1, b: 2); return AddLocal(b: m, a: m); int[||] AddLocal(int a, int b) { return a + b + x + y; } } }", @"class C { int N(int x) { int y = 10; var m = AddLocal(1, b: 2, x: x, y: y); return AddLocal(b: m, a: m, x: x, y: y); static int AddLocal(int a, int b, int x, int y) { return a + b + x + y; } } }" , parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestCallsWithDafaultValue() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { string y = ""; var m = AddLocal(1); return AddLocal(b: m); int[||] AddLocal(int a = 0, int b = 0) { return a + b + x + y.Length; } } }", @"class C { int N(int x) { string y = ""; var m = AddLocal(1, x: x, y: y); return AddLocal(b: m, x: x, y: y); static int AddLocal(int a = 0, int b = 0, int x = 0, string y = null) { return a + b + x + y.Length; } } }" , parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestWarningAnnotation() { await TestInRegularAndScriptAsync( @"class C { void N(int x) { Func<int> del = AddLocal; int [||]AddLocal() { return x + 1; } } }", @"class C { void N(int x) { Func<int> del = AddLocal; {|Warning:static int AddLocal(int x) { return x + 1; }|} } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestNonCamelCaseCapture() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int Static = 0; return AddLocal(); int [||]AddLocal() { return Static + 1; } } }", @"class C { int N(int x) { int Static = 0; return AddLocal(Static); static int AddLocal(int @static) { return @static + 1; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [WorkItem(46858, "https://github.com/dotnet/roslyn/issues/46858")] public async Task ShouldNotTriggerIfCallsOtherLocalFunction() { await TestMissingAsync( @"class C { int N(int x) { return AddLocal(); int [||]AddLocal() { B(); return x + 1; } void B() { } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestCallingStaticLocationFunction() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { return AddLocal(); int [||]AddLocal() { B(); return x + 1; } static void B() { } } }", @"class C { int N(int x) { return AddLocal(x); static int [||]AddLocal(int x) { B(); return x + 1; } static void B() { } } }", parseOptions: CSharp8ParseOptions); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.MakeLocalFunctionStatic; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeLocalFunctionStatic { public class MakeLocalFunctionStaticRefactoringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new MakeLocalFunctionStaticCodeRefactoringProvider(); private static readonly ParseOptions CSharp72ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_2); private static readonly ParseOptions CSharp8ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldNotTriggerForCSharp7() { await TestMissingAsync( @"class C { int N(int x) { return AddLocal(); int [||]AddLocal() { return x + 1; } } }", parameters: new TestParameters(parseOptions: CSharp72ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldNotTriggerIfNoCaptures() { await TestMissingAsync( @"class C { int N(int x) { return AddLocal(x); int [||]AddLocal(int x) { return x + 1; } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldNotTriggerIfAlreadyStatic() { await TestMissingAsync( @"class C { int N(int x) { return AddLocal(x); static int [||]AddLocal(int x) { return x + 1; } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldNotTriggerIfAlreadyStaticWithError() { await TestMissingAsync( @"class C { int N(int x) { return AddLocal(); static int [||]AddLocal() { return x + 1; } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldNotTriggerIfCapturesThisParameter() { await TestMissingAsync( @"class C { int x; int N() { return AddLocal(); int [||]AddLocal() { return x + 1; } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldTriggerIfExplicitlyPassedInThisParameter() { await TestInRegularAndScriptAsync( @"class C { int x; int N() { int y; return AddLocal(this); int [||]AddLocal(C c) { return c.x + y; } } }", @"class C { int x; int N() { int y; return AddLocal(this, y); static int [||]AddLocal(C c, int y) { return c.x + y; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldTriggerForCSharp8() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { return AddLocal(); int [||]AddLocal() { return x + 1; } } }", @"class C { int N(int x) { return AddLocal(x); static int AddLocal(int x) { return x + 1; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestMultipleVariables() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; return AddLocal(); int[||] AddLocal() { return x + y; } } }", @"class C { int N(int x) { int y = 10; return AddLocal(x, y); static int AddLocal(int x, int y) { return x + y; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestMultipleCalls() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; return AddLocal() + AddLocal(); int[||] AddLocal() { return x + y; } } }", @"class C { int N(int x) { int y = 10; return AddLocal(x, y) + AddLocal(x, y); static int AddLocal(int x, int y) { return x + y; } } }" , parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestMultipleCallsWithExistingParameters() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; var m = AddLocal(1, 2); return AddLocal(m, m); int[||] AddLocal(int a, int b) { return a + b + x + y; } } }", @"class C { int N(int x) { int y = 10; var m = AddLocal(1, 2, x, y); return AddLocal(m, m, x, y); static int AddLocal(int a, int b, int x, int y) { return a + b + x + y; } } }" , parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestRecursiveCall() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; var m = AddLocal(1, 2); return AddLocal(m, m); int[||] AddLocal(int a, int b) { return AddLocal(a, b) + x + y; } } }", @"class C { int N(int x) { int y = 10; var m = AddLocal(1, 2, x, y); return AddLocal(m, m, x, y); static int AddLocal(int a, int b, int x, int y) { return AddLocal(a, b, x, y) + x + y; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestCallInArgumentList() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; return AddLocal(AddLocal(1, 2), AddLocal(3, 4)); int[||] AddLocal(int a, int b) { return AddLocal(a, b) + x + y; } } }", @"class C { int N(int x) { int y = 10; return AddLocal(AddLocal(1, 2, x, y), AddLocal(3, 4, x, y), x, y); static int AddLocal(int a, int b, int x, int y) { return AddLocal(a, b, x, y) + x + y; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestCallsWithNamedArguments() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; var m = AddLocal(1, b: 2); return AddLocal(b: m, a: m); int[||] AddLocal(int a, int b) { return a + b + x + y; } } }", @"class C { int N(int x) { int y = 10; var m = AddLocal(1, b: 2, x: x, y: y); return AddLocal(b: m, a: m, x: x, y: y); static int AddLocal(int a, int b, int x, int y) { return a + b + x + y; } } }" , parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestCallsWithDafaultValue() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { string y = ""; var m = AddLocal(1); return AddLocal(b: m); int[||] AddLocal(int a = 0, int b = 0) { return a + b + x + y.Length; } } }", @"class C { int N(int x) { string y = ""; var m = AddLocal(1, x: x, y: y); return AddLocal(b: m, x: x, y: y); static int AddLocal(int a = 0, int b = 0, int x = 0, string y = null) { return a + b + x + y.Length; } } }" , parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestWarningAnnotation() { await TestInRegularAndScriptAsync( @"class C { void N(int x) { Func<int> del = AddLocal; int [||]AddLocal() { return x + 1; } } }", @"class C { void N(int x) { Func<int> del = AddLocal; {|Warning:static int AddLocal(int x) { return x + 1; }|} } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestNonCamelCaseCapture() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int Static = 0; return AddLocal(); int [||]AddLocal() { return Static + 1; } } }", @"class C { int N(int x) { int Static = 0; return AddLocal(Static); static int AddLocal(int @static) { return @static + 1; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [WorkItem(46858, "https://github.com/dotnet/roslyn/issues/46858")] public async Task ShouldNotTriggerIfCallsOtherLocalFunction() { await TestMissingAsync( @"class C { int N(int x) { return AddLocal(); int [||]AddLocal() { B(); return x + 1; } void B() { } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestCallingStaticLocationFunction() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { return AddLocal(); int [||]AddLocal() { B(); return x + 1; } static void B() { } } }", @"class C { int N(int x) { return AddLocal(x); static int [||]AddLocal(int x) { B(); return x + 1; } static void B() { } } }", parseOptions: CSharp8ParseOptions); } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/EventFieldDeclarationStructureTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure.MetadataAsSource { public class EventFieldDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<EventFieldDeclarationSyntax> { protected override string WorkspaceKind => CodeAnalysis.WorkspaceKind.MetadataAsSource; internal override AbstractSyntaxStructureProvider CreateProvider() => new EventFieldDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task NoCommentsOrAttributes() { const string code = @" class Goo { public event EventArgs $$goo }"; await VerifyNoBlockSpansAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithAttributes() { const string code = @" class Goo { {|hint:{|textspan:[Goo] |}event EventArgs $$goo|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithCommentsAndAttributes() { const string code = @" class Goo { {|hint:{|textspan:// Summary: // This is a summary. [Goo] |}event EventArgs $$goo|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithCommentsAttributesAndModifiers() { const string code = @" class Goo { {|hint:{|textspan:// Summary: // This is a summary. [Goo] |}public event EventArgs $$goo|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure.MetadataAsSource { public class EventFieldDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<EventFieldDeclarationSyntax> { protected override string WorkspaceKind => CodeAnalysis.WorkspaceKind.MetadataAsSource; internal override AbstractSyntaxStructureProvider CreateProvider() => new EventFieldDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task NoCommentsOrAttributes() { const string code = @" class Goo { public event EventArgs $$goo }"; await VerifyNoBlockSpansAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithAttributes() { const string code = @" class Goo { {|hint:{|textspan:[Goo] |}event EventArgs $$goo|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithCommentsAndAttributes() { const string code = @" class Goo { {|hint:{|textspan:// Summary: // This is a summary. [Goo] |}event EventArgs $$goo|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithCommentsAttributesAndModifiers() { const string code = @" class Goo { {|hint:{|textspan:// Summary: // This is a summary. [Goo] |}public event EventArgs $$goo|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Compilers/Core/Portable/PEWriter/LocalScope.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.Linq; using Microsoft.CodeAnalysis; namespace Microsoft.Cci { /// <summary> /// A range of CLR IL operations that comprise a lexical scope. /// </summary> internal struct LocalScope { /// <summary> /// The offset of the first operation in the scope. /// </summary> public readonly int StartOffset; /// <summary> /// The offset of the first operation outside of the scope, or the method body length. /// </summary> public readonly int EndOffset; private readonly ImmutableArray<ILocalDefinition> _constants; private readonly ImmutableArray<ILocalDefinition> _locals; internal LocalScope(int offset, int endOffset, ImmutableArray<ILocalDefinition> constants, ImmutableArray<ILocalDefinition> locals) { Debug.Assert(!locals.Any(l => l.Name == null)); Debug.Assert(!constants.Any(c => c.Name == null)); Debug.Assert(offset >= 0); Debug.Assert(endOffset > offset); StartOffset = offset; EndOffset = endOffset; _constants = constants; _locals = locals; } public int Length => EndOffset - StartOffset; /// <summary> /// Returns zero or more local constant definitions that are local to the given scope. /// </summary> public ImmutableArray<ILocalDefinition> Constants => _constants.NullToEmpty(); /// <summary> /// Returns zero or more local variable definitions that are local to the given scope. /// </summary> public ImmutableArray<ILocalDefinition> Variables => _locals.NullToEmpty(); } }
// Licensed to the .NET Foundation under one or more 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.Linq; using Microsoft.CodeAnalysis; namespace Microsoft.Cci { /// <summary> /// A range of CLR IL operations that comprise a lexical scope. /// </summary> internal struct LocalScope { /// <summary> /// The offset of the first operation in the scope. /// </summary> public readonly int StartOffset; /// <summary> /// The offset of the first operation outside of the scope, or the method body length. /// </summary> public readonly int EndOffset; private readonly ImmutableArray<ILocalDefinition> _constants; private readonly ImmutableArray<ILocalDefinition> _locals; internal LocalScope(int offset, int endOffset, ImmutableArray<ILocalDefinition> constants, ImmutableArray<ILocalDefinition> locals) { Debug.Assert(!locals.Any(l => l.Name == null)); Debug.Assert(!constants.Any(c => c.Name == null)); Debug.Assert(offset >= 0); Debug.Assert(endOffset > offset); StartOffset = offset; EndOffset = endOffset; _constants = constants; _locals = locals; } public int Length => EndOffset - StartOffset; /// <summary> /// Returns zero or more local constant definitions that are local to the given scope. /// </summary> public ImmutableArray<ILocalDefinition> Constants => _constants.NullToEmpty(); /// <summary> /// Returns zero or more local variable definitions that are local to the given scope. /// </summary> public ImmutableArray<ILocalDefinition> Variables => _locals.NullToEmpty(); } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Workspaces/Remote/ServiceHub/Services/ExtensionMethodImportCompletion/RemoteExtensionMethodImportCompletionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteExtensionMethodImportCompletionService : BrokeredServiceBase, IRemoteExtensionMethodImportCompletionService { internal sealed class Factory : FactoryBase<IRemoteExtensionMethodImportCompletionService> { protected override IRemoteExtensionMethodImportCompletionService CreateService(in ServiceConstructionArguments arguments) => new RemoteExtensionMethodImportCompletionService(arguments); } public RemoteExtensionMethodImportCompletionService(in ServiceConstructionArguments arguments) : base(arguments) { } public ValueTask<SerializableUnimportedExtensionMethods> GetUnimportedExtensionMethodsAsync( PinnedSolutionInfo solutionInfo, DocumentId documentId, int position, string receiverTypeSymbolKeyData, ImmutableArray<string> namespaceInScope, ImmutableArray<string> targetTypesSymbolKeyData, bool forceIndexCreation, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = solution.GetDocument(documentId)!; var compilation = await document.Project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var symbol = SymbolKey.ResolveString(receiverTypeSymbolKeyData, compilation, cancellationToken: cancellationToken).GetAnySymbol(); if (symbol is ITypeSymbol receiverTypeSymbol) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var namespaceInScopeSet = new HashSet<string>(namespaceInScope, syntaxFacts.StringComparer); var targetTypes = targetTypesSymbolKeyData .Select(symbolKey => SymbolKey.ResolveString(symbolKey, compilation, cancellationToken: cancellationToken).GetAnySymbol() as ITypeSymbol) .WhereNotNull().ToImmutableArray(); return await ExtensionMethodImportCompletionHelper.GetUnimportedExtensionMethodsInCurrentProcessAsync( document, position, receiverTypeSymbol, namespaceInScopeSet, targetTypes, forceIndexCreation, cancellationToken).ConfigureAwait(false); } return new SerializableUnimportedExtensionMethods(ImmutableArray<SerializableImportCompletionItem>.Empty, isPartialResult: false, getSymbolsTicks: 0, createItemsTicks: 0); }, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteExtensionMethodImportCompletionService : BrokeredServiceBase, IRemoteExtensionMethodImportCompletionService { internal sealed class Factory : FactoryBase<IRemoteExtensionMethodImportCompletionService> { protected override IRemoteExtensionMethodImportCompletionService CreateService(in ServiceConstructionArguments arguments) => new RemoteExtensionMethodImportCompletionService(arguments); } public RemoteExtensionMethodImportCompletionService(in ServiceConstructionArguments arguments) : base(arguments) { } public ValueTask<SerializableUnimportedExtensionMethods> GetUnimportedExtensionMethodsAsync( PinnedSolutionInfo solutionInfo, DocumentId documentId, int position, string receiverTypeSymbolKeyData, ImmutableArray<string> namespaceInScope, ImmutableArray<string> targetTypesSymbolKeyData, bool forceIndexCreation, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = solution.GetDocument(documentId)!; var compilation = await document.Project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var symbol = SymbolKey.ResolveString(receiverTypeSymbolKeyData, compilation, cancellationToken: cancellationToken).GetAnySymbol(); if (symbol is ITypeSymbol receiverTypeSymbol) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var namespaceInScopeSet = new HashSet<string>(namespaceInScope, syntaxFacts.StringComparer); var targetTypes = targetTypesSymbolKeyData .Select(symbolKey => SymbolKey.ResolveString(symbolKey, compilation, cancellationToken: cancellationToken).GetAnySymbol() as ITypeSymbol) .WhereNotNull().ToImmutableArray(); return await ExtensionMethodImportCompletionHelper.GetUnimportedExtensionMethodsInCurrentProcessAsync( document, position, receiverTypeSymbol, namespaceInScopeSet, targetTypes, forceIndexCreation, cancellationToken).ConfigureAwait(false); } return new SerializableUnimportedExtensionMethods(ImmutableArray<SerializableImportCompletionItem>.Empty, isPartialResult: false, getSymbolsTicks: 0, createItemsTicks: 0); }, cancellationToken); } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/EditorFeatures/Test/CodeFixes/ErrorCases/CodeFixExceptionInFixableDiagnosticIds.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeFixes.ErrorCases { public class ExceptionInFixableDiagnosticIds : CodeFixProvider { public sealed override ImmutableArray<string> FixableDiagnosticIds { get { throw new Exception($"Exception thrown in FixableDiagnosticIds of {nameof(ExceptionInFixableDiagnosticIds)}"); } } public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) => Task.FromResult(true); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeFixes.ErrorCases { public class ExceptionInFixableDiagnosticIds : CodeFixProvider { public sealed override ImmutableArray<string> FixableDiagnosticIds { get { throw new Exception($"Exception thrown in FixableDiagnosticIds of {nameof(ExceptionInFixableDiagnosticIds)}"); } } public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) => Task.FromResult(true); } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/EditorFeatures/CSharpTest/Structure/RegionDirectiveStructureTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class RegionDirectiveStructureTests : AbstractCSharpSyntaxNodeStructureTests<RegionDirectiveTriviaSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new RegionDirectiveStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task BrokenRegion() { const string code = @" $$#region Goo"; await VerifyNoBlockSpansAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task SimpleRegion() { const string code = @" {|span:$$#region Goo #endregion|}"; await VerifyBlockSpansAsync(code, Region("span", "Goo", autoCollapse: false, isDefaultCollapsed: true)); } [WorkItem(539361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539361")] [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task RegressionFor5284() { const string code = @" namespace BasicGenerateFromUsage { class BasicGenerateFromUsage { {|span:#reg$$ion TaoRegion static void Main(string[] args) { /*Marker1*/ CustomStack s = new CustomStack(); //Generate new class //Generate constructor Classic cc = new Classic(5, 6, 7);/*Marker2*/ Classic cc = new Classic(); //generate property cc.NewProperty = 5; /*Marker3*/ } #endregion TaoRegion|} } class Classic { } }"; await VerifyBlockSpansAsync(code, Region("span", "TaoRegion", autoCollapse: false, isDefaultCollapsed: true)); } [WorkItem(953668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/953668")] [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task RegionsShouldBeCollapsedByDefault() { const string code = @" class C { {|span:#region Re$$gion static void Main(string[] args) { } #endregion|} }"; await VerifyBlockSpansAsync(code, Region("span", "Region", autoCollapse: false, isDefaultCollapsed: true)); } [WorkItem(4105, "https://github.com/dotnet/roslyn/issues/4105")] [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task SpacesBetweenPoundAndRegionShouldNotAffectBanner() { const string code = @" class C { {|span:# region R$$egion static void Main(string[] args) { } # endregion|} }"; await VerifyBlockSpansAsync(code, Region("span", "Region", autoCollapse: false, isDefaultCollapsed: true)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class RegionDirectiveStructureTests : AbstractCSharpSyntaxNodeStructureTests<RegionDirectiveTriviaSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new RegionDirectiveStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task BrokenRegion() { const string code = @" $$#region Goo"; await VerifyNoBlockSpansAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task SimpleRegion() { const string code = @" {|span:$$#region Goo #endregion|}"; await VerifyBlockSpansAsync(code, Region("span", "Goo", autoCollapse: false, isDefaultCollapsed: true)); } [WorkItem(539361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539361")] [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task RegressionFor5284() { const string code = @" namespace BasicGenerateFromUsage { class BasicGenerateFromUsage { {|span:#reg$$ion TaoRegion static void Main(string[] args) { /*Marker1*/ CustomStack s = new CustomStack(); //Generate new class //Generate constructor Classic cc = new Classic(5, 6, 7);/*Marker2*/ Classic cc = new Classic(); //generate property cc.NewProperty = 5; /*Marker3*/ } #endregion TaoRegion|} } class Classic { } }"; await VerifyBlockSpansAsync(code, Region("span", "TaoRegion", autoCollapse: false, isDefaultCollapsed: true)); } [WorkItem(953668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/953668")] [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task RegionsShouldBeCollapsedByDefault() { const string code = @" class C { {|span:#region Re$$gion static void Main(string[] args) { } #endregion|} }"; await VerifyBlockSpansAsync(code, Region("span", "Region", autoCollapse: false, isDefaultCollapsed: true)); } [WorkItem(4105, "https://github.com/dotnet/roslyn/issues/4105")] [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task SpacesBetweenPoundAndRegionShouldNotAffectBanner() { const string code = @" class C { {|span:# region R$$egion static void Main(string[] args) { } # endregion|} }"; await VerifyBlockSpansAsync(code, Region("span", "Region", autoCollapse: false, isDefaultCollapsed: true)); } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/EditorFeatures/Core/Implementation/CommentSelection/CommentSelectionResult.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 Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection { internal readonly struct CommentSelectionResult { /// <summary> /// Text changes to make for this operation. /// </summary> public ImmutableArray<TextChange> TextChanges { get; } /// <summary> /// Tracking spans used to format and set the output selection after edits. /// </summary> public ImmutableArray<CommentTrackingSpan> TrackingSpans { get; } /// <summary> /// The type of text changes being made. /// This is known beforehand in some cases (comment selection) /// and determined after as a result in others (toggle comment). /// </summary> public Operation ResultOperation { get; } public CommentSelectionResult(IEnumerable<TextChange> textChanges, IEnumerable<CommentTrackingSpan> trackingSpans, Operation resultOperation) { TextChanges = textChanges.ToImmutableArray(); TrackingSpans = trackingSpans.ToImmutableArray(); ResultOperation = resultOperation; } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection { internal readonly struct CommentSelectionResult { /// <summary> /// Text changes to make for this operation. /// </summary> public ImmutableArray<TextChange> TextChanges { get; } /// <summary> /// Tracking spans used to format and set the output selection after edits. /// </summary> public ImmutableArray<CommentTrackingSpan> TrackingSpans { get; } /// <summary> /// The type of text changes being made. /// This is known beforehand in some cases (comment selection) /// and determined after as a result in others (toggle comment). /// </summary> public Operation ResultOperation { get; } public CommentSelectionResult(IEnumerable<TextChange> textChanges, IEnumerable<CommentTrackingSpan> trackingSpans, Operation resultOperation) { TextChanges = textChanges.ToImmutableArray(); TrackingSpans = trackingSpans.ToImmutableArray(); ResultOperation = resultOperation; } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./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
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Analyzers/CSharp/CodeFixes/RemoveUnreachableCode/CSharpRemoveUnreachableCodeCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.RemoveUnreachableCode { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveUnreachableCode), Shared] internal class CSharpRemoveUnreachableCodeCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpRemoveUnreachableCodeCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.RemoveUnreachableCodeDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality; public override Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics[0]; #if CODE_STYLE // 'CodeActionPriority' is not a public API, hence not supported in CodeStyle layer. // https://github.com/dotnet/roslyn/issues/42431 tracks adding a public API. var codeAction = new MyCodeAction( CSharpCodeFixesResources.Remove_unreachable_code, c => FixAsync(context.Document, diagnostic, c)); #else // Only the first reported unreacha ble line will have a squiggle. On that line, make the // code action normal priority as the user is likely bringing up the lightbulb to fix the // squiggle. On all the other lines make the code action low priority as it's definitely // helpful, but shouldn't interfere with anything else the uesr is doing. var priority = IsSubsequentSection(diagnostic) ? CodeActionPriority.Low : CodeActionPriority.Medium; var codeAction = new MyCodeAction( CSharpCodeFixesResources.Remove_unreachable_code, c => FixAsync(context.Document, diagnostic, c), priority); #endif context.RegisterCodeFix(codeAction, diagnostic); return Task.CompletedTask; } protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !IsSubsequentSection(diagnostic); private static bool IsSubsequentSection(Diagnostic diagnostic) => diagnostic.Properties.ContainsKey(CSharpRemoveUnreachableCodeDiagnosticAnalyzer.IsSubsequentSection); protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) { var firstUnreachableStatementLocation = diagnostic.AdditionalLocations.First(); var firstUnreachableStatement = (StatementSyntax)firstUnreachableStatementLocation.FindNode(cancellationToken); RemoveStatement(editor, firstUnreachableStatement); var sections = RemoveUnreachableCodeHelpers.GetSubsequentUnreachableSections(firstUnreachableStatement); foreach (var section in sections) { foreach (var statement in section) { RemoveStatement(editor, statement); } } } return Task.CompletedTask; // Local function static void RemoveStatement(SyntaxEditor editor, SyntaxNode statement) { if (!statement.IsParentKind(SyntaxKind.Block) && !statement.IsParentKind(SyntaxKind.SwitchSection)) { editor.ReplaceNode(statement, SyntaxFactory.Block()); } else { editor.RemoveNode(statement, SyntaxRemoveOptions.KeepUnbalancedDirectives); } } } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { #if CODE_STYLE // 'CodeActionPriority' is not a public API, hence not supported in CodeStyle layer. // https://github.com/dotnet/roslyn/issues/42431 tracks adding a public API. public MyCodeAction( string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } #else public MyCodeAction( string title, Func<CancellationToken, Task<Document>> createChangedDocument, CodeActionPriority priority) : base(title, createChangedDocument, title) { Priority = priority; } internal override CodeActionPriority Priority { get; } #endif } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.RemoveUnreachableCode { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveUnreachableCode), Shared] internal class CSharpRemoveUnreachableCodeCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpRemoveUnreachableCodeCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.RemoveUnreachableCodeDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality; public override Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics[0]; #if CODE_STYLE // 'CodeActionPriority' is not a public API, hence not supported in CodeStyle layer. // https://github.com/dotnet/roslyn/issues/42431 tracks adding a public API. var codeAction = new MyCodeAction( CSharpCodeFixesResources.Remove_unreachable_code, c => FixAsync(context.Document, diagnostic, c)); #else // Only the first reported unreacha ble line will have a squiggle. On that line, make the // code action normal priority as the user is likely bringing up the lightbulb to fix the // squiggle. On all the other lines make the code action low priority as it's definitely // helpful, but shouldn't interfere with anything else the uesr is doing. var priority = IsSubsequentSection(diagnostic) ? CodeActionPriority.Low : CodeActionPriority.Medium; var codeAction = new MyCodeAction( CSharpCodeFixesResources.Remove_unreachable_code, c => FixAsync(context.Document, diagnostic, c), priority); #endif context.RegisterCodeFix(codeAction, diagnostic); return Task.CompletedTask; } protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !IsSubsequentSection(diagnostic); private static bool IsSubsequentSection(Diagnostic diagnostic) => diagnostic.Properties.ContainsKey(CSharpRemoveUnreachableCodeDiagnosticAnalyzer.IsSubsequentSection); protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) { var firstUnreachableStatementLocation = diagnostic.AdditionalLocations.First(); var firstUnreachableStatement = (StatementSyntax)firstUnreachableStatementLocation.FindNode(cancellationToken); RemoveStatement(editor, firstUnreachableStatement); var sections = RemoveUnreachableCodeHelpers.GetSubsequentUnreachableSections(firstUnreachableStatement); foreach (var section in sections) { foreach (var statement in section) { RemoveStatement(editor, statement); } } } return Task.CompletedTask; // Local function static void RemoveStatement(SyntaxEditor editor, SyntaxNode statement) { if (!statement.IsParentKind(SyntaxKind.Block) && !statement.IsParentKind(SyntaxKind.SwitchSection)) { editor.ReplaceNode(statement, SyntaxFactory.Block()); } else { editor.RemoveNode(statement, SyntaxRemoveOptions.KeepUnbalancedDirectives); } } } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { #if CODE_STYLE // 'CodeActionPriority' is not a public API, hence not supported in CodeStyle layer. // https://github.com/dotnet/roslyn/issues/42431 tracks adding a public API. public MyCodeAction( string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } #else public MyCodeAction( string title, Func<CancellationToken, Task<Document>> createChangedDocument, CodeActionPriority priority) : base(title, createChangedDocument, title) { Priority = priority; } internal override CodeActionPriority Priority { get; } #endif } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.ActiveFileState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { /// <summary> /// state that is responsible to hold onto local diagnostics data regarding active/opened files (depends on host) /// in memory. /// </summary> private sealed class ActiveFileState { // file state this is for public readonly DocumentId DocumentId; // analysis data for each kind private DocumentAnalysisData _syntax = DocumentAnalysisData.Empty; private DocumentAnalysisData _semantic = DocumentAnalysisData.Empty; public ActiveFileState(DocumentId documentId) => DocumentId = documentId; public bool IsEmpty => _syntax.Items.IsEmpty && _semantic.Items.IsEmpty; public void ResetVersion() { // reset version of cached data so that we can recalculate new data (ex, OnDocumentReset) _syntax = new DocumentAnalysisData(VersionStamp.Default, _syntax.Items); _semantic = new DocumentAnalysisData(VersionStamp.Default, _semantic.Items); } public DocumentAnalysisData GetAnalysisData(AnalysisKind kind) => kind switch { AnalysisKind.Syntax => _syntax, AnalysisKind.Semantic => _semantic, _ => throw ExceptionUtilities.UnexpectedValue(kind) }; public void Save(AnalysisKind kind, DocumentAnalysisData data) { Contract.ThrowIfFalse(data.OldItems.IsDefault); switch (kind) { case AnalysisKind.Syntax: _syntax = data; return; case AnalysisKind.Semantic: _semantic = data; return; default: throw ExceptionUtilities.UnexpectedValue(kind); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { /// <summary> /// state that is responsible to hold onto local diagnostics data regarding active/opened files (depends on host) /// in memory. /// </summary> private sealed class ActiveFileState { // file state this is for public readonly DocumentId DocumentId; // analysis data for each kind private DocumentAnalysisData _syntax = DocumentAnalysisData.Empty; private DocumentAnalysisData _semantic = DocumentAnalysisData.Empty; public ActiveFileState(DocumentId documentId) => DocumentId = documentId; public bool IsEmpty => _syntax.Items.IsEmpty && _semantic.Items.IsEmpty; public void ResetVersion() { // reset version of cached data so that we can recalculate new data (ex, OnDocumentReset) _syntax = new DocumentAnalysisData(VersionStamp.Default, _syntax.Items); _semantic = new DocumentAnalysisData(VersionStamp.Default, _semantic.Items); } public DocumentAnalysisData GetAnalysisData(AnalysisKind kind) => kind switch { AnalysisKind.Syntax => _syntax, AnalysisKind.Semantic => _semantic, _ => throw ExceptionUtilities.UnexpectedValue(kind) }; public void Save(AnalysisKind kind, DocumentAnalysisData data) { Contract.ThrowIfFalse(data.OldItems.IsDefault); switch (kind) { case AnalysisKind.Syntax: _syntax = data; return; case AnalysisKind.Semantic: _semantic = data; return; default: throw ExceptionUtilities.UnexpectedValue(kind); } } } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Results/CheckedDirectTrySpecificConversions.txt
-=-=-=-=-=-=-=-=- DirectCast(SByte, SByte) -> SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { Parameter( x type: System.SByte ) } return type: System.SByte type: System.Func`2[System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- CByte(SByte) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { ConvertChecked( Parameter( x type: System.SByte ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.SByte,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(SByte) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { ConvertChecked( Parameter( x type: System.SByte ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.SByte,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(SByte) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.SByte,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(SByte) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { ConvertChecked( Parameter( x type: System.SByte ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.SByte,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(SByte) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { Convert( ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.SByte,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(SByte) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { Convert( Parameter( x type: System.SByte ) type: System.Single ) } return type: System.Single type: System.Func`2[System.SByte,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(SByte) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { Convert( Parameter( x type: System.SByte ) type: System.Double ) } return type: System.Double type: System.Func`2[System.SByte,System.Double] ) -=-=-=-=-=-=-=-=- CDec(SByte) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { Convert( ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.SByte,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(SByte) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { Convert( ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.SByte,System.String] ) -=-=-=-=-=-=-=-=- TryCast(SByte, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { TypeAs( Parameter( x type: System.SByte ) type: System.Object ) } return type: System.Object type: System.Func`2[System.SByte,System.Object] ) -=-=-=-=-=-=-=-=- CObj(SByte) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { Convert( Parameter( x type: System.SByte ) type: System.Object ) } return type: System.Object type: System.Func`2[System.SByte,System.Object] ) -=-=-=-=-=-=-=-=- DirectCast(SByte?, SByte?) -> SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { Parameter( x type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`2[System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- CByte(SByte?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.SByte],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(SByte?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.SByte],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(SByte?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.SByte],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(SByte?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.SByte],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(SByte?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.SByte],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(SByte?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.SByte],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(SByte?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.SByte],System.Double] ) -=-=-=-=-=-=-=-=- CDec(SByte?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.SByte],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(SByte?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.SByte],System.String] ) -=-=-=-=-=-=-=-=- TryCast(SByte?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.SByte] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.SByte],System.Object] ) -=-=-=-=-=-=-=-=- CObj(SByte?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { Convert( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.SByte],System.Object] ) -=-=-=-=-=-=-=-=- DirectCast(E_SByte, E_SByte) -> E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { Parameter( x type: E_SByte ) } return type: E_SByte type: System.Func`2[E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- CByte(E_SByte) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { ConvertChecked( Parameter( x type: E_SByte ) type: System.Byte ) } return type: System.Byte type: System.Func`2[E_SByte,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_SByte) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { ConvertChecked( Parameter( x type: E_SByte ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[E_SByte,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(E_SByte) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { ConvertChecked( Parameter( x type: E_SByte ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[E_SByte,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(E_SByte) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { ConvertChecked( Parameter( x type: E_SByte ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[E_SByte,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_SByte) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { Convert( ConvertChecked( Parameter( x type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[E_SByte,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_SByte) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { Convert( Parameter( x type: E_SByte ) type: System.Single ) } return type: System.Single type: System.Func`2[E_SByte,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_SByte) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { Convert( Parameter( x type: E_SByte ) type: System.Double ) } return type: System.Double type: System.Func`2[E_SByte,System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_SByte) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { Convert( ConvertChecked( Parameter( x type: E_SByte ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[E_SByte,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_SByte) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { Convert( ConvertChecked( Parameter( x type: E_SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[E_SByte,System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_SByte, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { TypeAs( Parameter( x type: E_SByte ) type: System.Object ) } return type: System.Object type: System.Func`2[E_SByte,System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_SByte) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { Convert( Parameter( x type: E_SByte ) type: System.Object ) } return type: System.Object type: System.Func`2[E_SByte,System.Object] ) -=-=-=-=-=-=-=-=- DirectCast(E_SByte?, E_SByte?) -> E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { Parameter( x type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`2[System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- CByte(E_SByte?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[E_SByte],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_SByte?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[E_SByte],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(E_SByte?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[E_SByte],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(E_SByte?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[E_SByte],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_SByte?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[E_SByte],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_SByte?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[E_SByte],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_SByte?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[E_SByte],System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_SByte?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[E_SByte],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_SByte?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_SByte],System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_SByte?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { TypeAs( Parameter( x type: System.Nullable`1[E_SByte] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_SByte],System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_SByte?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_SByte],System.Object] ) -=-=-=-=-=-=-=-=- DirectCast(Byte, Byte) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Parameter( x type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- CByte(Byte) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Parameter( x type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Byte) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { ConvertChecked( Parameter( x type: System.Byte ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Byte,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Byte) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { ConvertChecked( Parameter( x type: System.Byte ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Byte,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Byte) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { ConvertChecked( Parameter( x type: System.Byte ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Byte,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Byte) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Convert( ConvertChecked( Parameter( x type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Byte,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Byte) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Convert( Parameter( x type: System.Byte ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Byte,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Byte) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Convert( Parameter( x type: System.Byte ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Byte,System.Double] ) -=-=-=-=-=-=-=-=- CDec(Byte) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Convert( ConvertChecked( Parameter( x type: System.Byte ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Byte,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Byte) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Convert( Parameter( x type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Byte,System.String] ) -=-=-=-=-=-=-=-=- TryCast(Byte, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { TypeAs( Parameter( x type: System.Byte ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Byte,System.Object] ) -=-=-=-=-=-=-=-=- CObj(Byte) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Convert( Parameter( x type: System.Byte ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Byte,System.Object] ) -=-=-=-=-=-=-=-=- CByte(Byte?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.Byte],System.Byte] ) -=-=-=-=-=-=-=-=- DirectCast(Byte?, Byte?) -> Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { Parameter( x type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`2[System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- CShort(Byte?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) method: Byte op_Explicit(System.Nullable`1[System.Byte]) in System.Nullable`1[System.Byte] type: System.Byte ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.Byte],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Byte?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) method: Byte op_Explicit(System.Nullable`1[System.Byte]) in System.Nullable`1[System.Byte] type: System.Byte ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.Byte],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Byte?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) method: Byte op_Explicit(System.Nullable`1[System.Byte]) in System.Nullable`1[System.Byte] type: System.Byte ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.Byte],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Byte?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) method: Byte op_Explicit(System.Nullable`1[System.Byte]) in System.Nullable`1[System.Byte] type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.Byte],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Byte?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) method: Byte op_Explicit(System.Nullable`1[System.Byte]) in System.Nullable`1[System.Byte] type: System.Byte ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.Byte],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Byte?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) method: Byte op_Explicit(System.Nullable`1[System.Byte]) in System.Nullable`1[System.Byte] type: System.Byte ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.Byte],System.Double] ) -=-=-=-=-=-=-=-=- CDec(Byte?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) method: Byte op_Explicit(System.Nullable`1[System.Byte]) in System.Nullable`1[System.Byte] type: System.Byte ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.Byte],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Byte?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) method: Byte op_Explicit(System.Nullable`1[System.Byte]) in System.Nullable`1[System.Byte] type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Byte],System.String] ) -=-=-=-=-=-=-=-=- TryCast(Byte?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.Byte] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Byte],System.Object] ) -=-=-=-=-=-=-=-=- CObj(Byte?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { Convert( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Byte],System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_Byte) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { ConvertChecked( Parameter( x type: E_Byte ) type: System.Byte ) } return type: System.Byte type: System.Func`2[E_Byte,System.Byte] ) -=-=-=-=-=-=-=-=- DirectCast(E_Byte, E_Byte) -> E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { Parameter( x type: E_Byte ) } return type: E_Byte type: System.Func`2[E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- CShort(E_Byte) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { ConvertChecked( Parameter( x type: E_Byte ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[E_Byte,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(E_Byte) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { ConvertChecked( Parameter( x type: E_Byte ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[E_Byte,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(E_Byte) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { ConvertChecked( Parameter( x type: E_Byte ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[E_Byte,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_Byte) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { Convert( ConvertChecked( Parameter( x type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[E_Byte,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_Byte) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { Convert( Parameter( x type: E_Byte ) type: System.Single ) } return type: System.Single type: System.Func`2[E_Byte,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_Byte) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { Convert( Parameter( x type: E_Byte ) type: System.Double ) } return type: System.Double type: System.Func`2[E_Byte,System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_Byte) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { Convert( ConvertChecked( Parameter( x type: E_Byte ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[E_Byte,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_Byte) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { Convert( ConvertChecked( Parameter( x type: E_Byte ) type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[E_Byte,System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_Byte, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { TypeAs( Parameter( x type: E_Byte ) type: System.Object ) } return type: System.Object type: System.Func`2[E_Byte,System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_Byte) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { Convert( Parameter( x type: E_Byte ) type: System.Object ) } return type: System.Object type: System.Func`2[E_Byte,System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_Byte?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[E_Byte],System.Byte] ) -=-=-=-=-=-=-=-=- DirectCast(E_Byte?, E_Byte?) -> E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { Parameter( x type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`2[System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- CShort(E_Byte?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[E_Byte],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(E_Byte?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[E_Byte],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(E_Byte?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[E_Byte],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_Byte?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[E_Byte],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_Byte?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[E_Byte],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_Byte?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[E_Byte],System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_Byte?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[E_Byte],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_Byte?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Byte],System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_Byte?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { TypeAs( Parameter( x type: System.Nullable`1[E_Byte] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_Byte],System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_Byte?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_Byte],System.Object] ) -=-=-=-=-=-=-=-=- CByte(Short) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { ConvertChecked( Parameter( x type: System.Int16 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Int16,System.Byte] ) -=-=-=-=-=-=-=-=- DirectCast(Short, Short) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Parameter( x type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- CShort(Short) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Parameter( x type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Short) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { ConvertChecked( Parameter( x type: System.Int16 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Int16,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Short) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { ConvertChecked( Parameter( x type: System.Int16 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Int16,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Short) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Convert( ConvertChecked( Parameter( x type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Int16,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Short) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Convert( Parameter( x type: System.Int16 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Int16,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Short) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Convert( Parameter( x type: System.Int16 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Int16,System.Double] ) -=-=-=-=-=-=-=-=- CDec(Short) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Convert( ConvertChecked( Parameter( x type: System.Int16 ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Int16,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Short) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Convert( ConvertChecked( Parameter( x type: System.Int16 ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Int16,System.String] ) -=-=-=-=-=-=-=-=- TryCast(Short, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { TypeAs( Parameter( x type: System.Int16 ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Int16,System.Object] ) -=-=-=-=-=-=-=-=- CObj(Short) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Convert( Parameter( x type: System.Int16 ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Int16,System.Object] ) -=-=-=-=-=-=-=-=- CByte(Short?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int16] ) method: Int16 op_Explicit(System.Nullable`1[System.Int16]) in System.Nullable`1[System.Int16] type: System.Int16 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.Int16],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Short?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { ConvertChecked( Parameter( x type: System.Nullable`1[System.Int16] ) Lifted type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.Int16],System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(Short?, Short?) -> Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { Parameter( x type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`2[System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- CInt(Short?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int16] ) method: Int16 op_Explicit(System.Nullable`1[System.Int16]) in System.Nullable`1[System.Int16] type: System.Int16 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.Int16],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Short?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int16] ) method: Int16 op_Explicit(System.Nullable`1[System.Int16]) in System.Nullable`1[System.Int16] type: System.Int16 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.Int16],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Short?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int16] ) method: Int16 op_Explicit(System.Nullable`1[System.Int16]) in System.Nullable`1[System.Int16] type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.Int16],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Short?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int16] ) method: Int16 op_Explicit(System.Nullable`1[System.Int16]) in System.Nullable`1[System.Int16] type: System.Int16 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.Int16],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Short?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int16] ) method: Int16 op_Explicit(System.Nullable`1[System.Int16]) in System.Nullable`1[System.Int16] type: System.Int16 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.Int16],System.Double] ) -=-=-=-=-=-=-=-=- CDec(Short?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int16] ) method: Int16 op_Explicit(System.Nullable`1[System.Int16]) in System.Nullable`1[System.Int16] type: System.Int16 ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.Int16],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Short?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int16] ) method: Int16 op_Explicit(System.Nullable`1[System.Int16]) in System.Nullable`1[System.Int16] type: System.Int16 ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Int16],System.String] ) -=-=-=-=-=-=-=-=- TryCast(Short?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.Int16] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Int16],System.Object] ) -=-=-=-=-=-=-=-=- CObj(Short?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { Convert( Parameter( x type: System.Nullable`1[System.Int16] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Int16],System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_Short) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { ConvertChecked( Parameter( x type: E_Short ) type: System.Byte ) } return type: System.Byte type: System.Func`2[E_Short,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_Short) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { ConvertChecked( Parameter( x type: E_Short ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[E_Short,System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(E_Short, E_Short) -> E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { Parameter( x type: E_Short ) } return type: E_Short type: System.Func`2[E_Short,E_Short] ) -=-=-=-=-=-=-=-=- CInt(E_Short) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { ConvertChecked( Parameter( x type: E_Short ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[E_Short,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(E_Short) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { ConvertChecked( Parameter( x type: E_Short ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[E_Short,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_Short) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { Convert( ConvertChecked( Parameter( x type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[E_Short,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_Short) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { Convert( Parameter( x type: E_Short ) type: System.Single ) } return type: System.Single type: System.Func`2[E_Short,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_Short) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { Convert( Parameter( x type: E_Short ) type: System.Double ) } return type: System.Double type: System.Func`2[E_Short,System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_Short) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { Convert( ConvertChecked( Parameter( x type: E_Short ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[E_Short,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_Short) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { Convert( ConvertChecked( Parameter( x type: E_Short ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[E_Short,System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_Short, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { TypeAs( Parameter( x type: E_Short ) type: System.Object ) } return type: System.Object type: System.Func`2[E_Short,System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_Short) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { Convert( Parameter( x type: E_Short ) type: System.Object ) } return type: System.Object type: System.Func`2[E_Short,System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_Short?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[E_Short],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_Short?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[E_Short],System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(E_Short?, E_Short?) -> E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { Parameter( x type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`2[System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- CInt(E_Short?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[E_Short],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(E_Short?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[E_Short],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_Short?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[E_Short],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_Short?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[E_Short],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_Short?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[E_Short],System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_Short?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[E_Short],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_Short?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Short],System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_Short?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { TypeAs( Parameter( x type: System.Nullable`1[E_Short] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_Short],System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_Short?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_Short],System.Object] ) -=-=-=-=-=-=-=-=- CByte(UShort) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { ConvertChecked( Parameter( x type: System.UInt16 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.UInt16,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(UShort) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { ConvertChecked( Parameter( x type: System.UInt16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.UInt16,System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(UShort, UShort) -> UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { Parameter( x type: System.UInt16 ) } return type: System.UInt16 type: System.Func`2[System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- CInt(UShort) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { ConvertChecked( Parameter( x type: System.UInt16 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.UInt16,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(UShort) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { ConvertChecked( Parameter( x type: System.UInt16 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.UInt16,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(UShort) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { Convert( ConvertChecked( Parameter( x type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.UInt16,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(UShort) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { Convert( Parameter( x type: System.UInt16 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.UInt16,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(UShort) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { Convert( Parameter( x type: System.UInt16 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.UInt16,System.Double] ) -=-=-=-=-=-=-=-=- CDec(UShort) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { Convert( ConvertChecked( Parameter( x type: System.UInt16 ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.UInt16,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(UShort) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { Convert( ConvertChecked( Parameter( x type: System.UInt16 ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.UInt16,System.String] ) -=-=-=-=-=-=-=-=- TryCast(UShort, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { TypeAs( Parameter( x type: System.UInt16 ) type: System.Object ) } return type: System.Object type: System.Func`2[System.UInt16,System.Object] ) -=-=-=-=-=-=-=-=- CObj(UShort) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { Convert( Parameter( x type: System.UInt16 ) type: System.Object ) } return type: System.Object type: System.Func`2[System.UInt16,System.Object] ) -=-=-=-=-=-=-=-=- CByte(UShort?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.UInt16],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(UShort?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.UInt16],System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(UShort?, UShort?) -> UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { Parameter( x type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`2[System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- CInt(UShort?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.UInt16],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(UShort?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.UInt16],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(UShort?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.UInt16],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(UShort?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.UInt16],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(UShort?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.UInt16],System.Double] ) -=-=-=-=-=-=-=-=- CDec(UShort?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.UInt16],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(UShort?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.UInt16],System.String] ) -=-=-=-=-=-=-=-=- TryCast(UShort?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.UInt16] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.UInt16],System.Object] ) -=-=-=-=-=-=-=-=- CObj(UShort?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { Convert( Parameter( x type: System.Nullable`1[System.UInt16] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.UInt16],System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_UShort) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { ConvertChecked( Parameter( x type: E_UShort ) type: System.Byte ) } return type: System.Byte type: System.Func`2[E_UShort,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_UShort) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { ConvertChecked( Parameter( x type: E_UShort ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[E_UShort,System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(E_UShort, E_UShort) -> E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { Parameter( x type: E_UShort ) } return type: E_UShort type: System.Func`2[E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- CInt(E_UShort) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { ConvertChecked( Parameter( x type: E_UShort ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[E_UShort,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(E_UShort) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { ConvertChecked( Parameter( x type: E_UShort ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[E_UShort,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_UShort) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { Convert( ConvertChecked( Parameter( x type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[E_UShort,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_UShort) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { Convert( Parameter( x type: E_UShort ) type: System.Single ) } return type: System.Single type: System.Func`2[E_UShort,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_UShort) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { Convert( Parameter( x type: E_UShort ) type: System.Double ) } return type: System.Double type: System.Func`2[E_UShort,System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_UShort) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { Convert( ConvertChecked( Parameter( x type: E_UShort ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[E_UShort,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_UShort) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { Convert( ConvertChecked( Parameter( x type: E_UShort ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[E_UShort,System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_UShort, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { TypeAs( Parameter( x type: E_UShort ) type: System.Object ) } return type: System.Object type: System.Func`2[E_UShort,System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_UShort) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { Convert( Parameter( x type: E_UShort ) type: System.Object ) } return type: System.Object type: System.Func`2[E_UShort,System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_UShort?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[E_UShort],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_UShort?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[E_UShort],System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(E_UShort?, E_UShort?) -> E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { Parameter( x type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`2[System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- CInt(E_UShort?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[E_UShort],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(E_UShort?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[E_UShort],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_UShort?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[E_UShort],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_UShort?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[E_UShort],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_UShort?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[E_UShort],System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_UShort?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[E_UShort],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_UShort?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_UShort],System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_UShort?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { TypeAs( Parameter( x type: System.Nullable`1[E_UShort] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_UShort],System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_UShort?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_UShort],System.Object] ) -=-=-=-=-=-=-=-=- CByte(Integer) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { ConvertChecked( Parameter( x type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Int32,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Integer) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { ConvertChecked( Parameter( x type: System.Int32 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Int32,System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(Integer, Integer) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Parameter( x type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- CInt(Integer) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Parameter( x type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Integer) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { ConvertChecked( Parameter( x type: System.Int32 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Int32,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Integer) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Convert( Parameter( x type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Int32,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Integer) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Convert( Parameter( x type: System.Int32 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Int32,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Integer) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Convert( Parameter( x type: System.Int32 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Int32,System.Double] ) -=-=-=-=-=-=-=-=- CDec(Integer) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Convert( Parameter( x type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Int32,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Integer) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Convert( Parameter( x type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Int32,System.String] ) -=-=-=-=-=-=-=-=- TryCast(Integer, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { TypeAs( Parameter( x type: System.Int32 ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Int32,System.Object] ) -=-=-=-=-=-=-=-=- CObj(Integer) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Convert( Parameter( x type: System.Int32 ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Int32,System.Object] ) -=-=-=-=-=-=-=-=- CByte(Integer?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int32] ) method: Int32 op_Explicit(System.Nullable`1[System.Int32]) in System.Nullable`1[System.Int32] type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.Int32],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Integer?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int32] ) method: Int32 op_Explicit(System.Nullable`1[System.Int32]) in System.Nullable`1[System.Int32] type: System.Int32 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.Int32],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Integer?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { ConvertChecked( Parameter( x type: System.Nullable`1[System.Int32] ) Lifted type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.Int32],System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(Integer?, Integer?) -> Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { Parameter( x type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`2[System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- CLng(Integer?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int32] ) method: Int32 op_Explicit(System.Nullable`1[System.Int32]) in System.Nullable`1[System.Int32] type: System.Int32 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.Int32],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Integer?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int32] ) method: Int32 op_Explicit(System.Nullable`1[System.Int32]) in System.Nullable`1[System.Int32] type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.Int32],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Integer?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int32] ) method: Int32 op_Explicit(System.Nullable`1[System.Int32]) in System.Nullable`1[System.Int32] type: System.Int32 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.Int32],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Integer?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int32] ) method: Int32 op_Explicit(System.Nullable`1[System.Int32]) in System.Nullable`1[System.Int32] type: System.Int32 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.Int32],System.Double] ) -=-=-=-=-=-=-=-=- CDec(Integer?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int32] ) method: Int32 op_Explicit(System.Nullable`1[System.Int32]) in System.Nullable`1[System.Int32] type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.Int32],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Integer?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int32] ) method: Int32 op_Explicit(System.Nullable`1[System.Int32]) in System.Nullable`1[System.Int32] type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Int32],System.String] ) -=-=-=-=-=-=-=-=- TryCast(Integer?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.Int32] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Int32],System.Object] ) -=-=-=-=-=-=-=-=- CObj(Integer?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { Convert( Parameter( x type: System.Nullable`1[System.Int32] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Int32],System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_Integer) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { ConvertChecked( Parameter( x type: E_Integer ) type: System.Byte ) } return type: System.Byte type: System.Func`2[E_Integer,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_Integer) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { ConvertChecked( Parameter( x type: E_Integer ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[E_Integer,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(E_Integer) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { ConvertChecked( Parameter( x type: E_Integer ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[E_Integer,System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(E_Integer, E_Integer) -> E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { Parameter( x type: E_Integer ) } return type: E_Integer type: System.Func`2[E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- CLng(E_Integer) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { ConvertChecked( Parameter( x type: E_Integer ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[E_Integer,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_Integer) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { Convert( ConvertChecked( Parameter( x type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[E_Integer,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_Integer) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { Convert( Parameter( x type: E_Integer ) type: System.Single ) } return type: System.Single type: System.Func`2[E_Integer,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_Integer) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { Convert( Parameter( x type: E_Integer ) type: System.Double ) } return type: System.Double type: System.Func`2[E_Integer,System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_Integer) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { Convert( ConvertChecked( Parameter( x type: E_Integer ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[E_Integer,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_Integer) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { Convert( ConvertChecked( Parameter( x type: E_Integer ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[E_Integer,System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_Integer, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { TypeAs( Parameter( x type: E_Integer ) type: System.Object ) } return type: System.Object type: System.Func`2[E_Integer,System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_Integer) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { Convert( Parameter( x type: E_Integer ) type: System.Object ) } return type: System.Object type: System.Func`2[E_Integer,System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_Integer?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[E_Integer],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_Integer?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[E_Integer],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(E_Integer?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[E_Integer],System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(E_Integer?, E_Integer?) -> E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { Parameter( x type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`2[System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- CLng(E_Integer?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[E_Integer],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_Integer?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[E_Integer],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_Integer?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[E_Integer],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_Integer?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[E_Integer],System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_Integer?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[E_Integer],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_Integer?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Integer],System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_Integer?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { TypeAs( Parameter( x type: System.Nullable`1[E_Integer] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_Integer],System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_Integer?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_Integer],System.Object] ) -=-=-=-=-=-=-=-=- CByte(UInteger) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { ConvertChecked( Parameter( x type: System.UInt32 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.UInt32,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(UInteger) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { ConvertChecked( Parameter( x type: System.UInt32 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.UInt32,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(UInteger) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { ConvertChecked( Parameter( x type: System.UInt32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.UInt32,System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(UInteger, UInteger) -> UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { Parameter( x type: System.UInt32 ) } return type: System.UInt32 type: System.Func`2[System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- CLng(UInteger) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { ConvertChecked( Parameter( x type: System.UInt32 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.UInt32,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(UInteger) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { Convert( Parameter( x type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.UInt32,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(UInteger) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { Convert( Parameter( x type: System.UInt32 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.UInt32,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(UInteger) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { Convert( Parameter( x type: System.UInt32 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.UInt32,System.Double] ) -=-=-=-=-=-=-=-=- CDec(UInteger) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { Convert( Parameter( x type: System.UInt32 ) method: System.Decimal op_Implicit(UInt32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.UInt32,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(UInteger) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { Convert( Parameter( x type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.UInt32,System.String] ) -=-=-=-=-=-=-=-=- TryCast(UInteger, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { TypeAs( Parameter( x type: System.UInt32 ) type: System.Object ) } return type: System.Object type: System.Func`2[System.UInt32,System.Object] ) -=-=-=-=-=-=-=-=- CObj(UInteger) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { Convert( Parameter( x type: System.UInt32 ) type: System.Object ) } return type: System.Object type: System.Func`2[System.UInt32,System.Object] ) -=-=-=-=-=-=-=-=- CByte(UInteger?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.UInt32],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(UInteger?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.UInt32],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(UInteger?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.UInt32],System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(UInteger?, UInteger?) -> UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { Parameter( x type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`2[System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- CLng(UInteger?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.UInt32],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(UInteger?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.UInt32],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(UInteger?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.UInt32],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(UInteger?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.UInt32],System.Double] ) -=-=-=-=-=-=-=-=- CDec(UInteger?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) method: System.Decimal op_Implicit(UInt32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.UInt32],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(UInteger?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.UInt32],System.String] ) -=-=-=-=-=-=-=-=- TryCast(UInteger?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.UInt32] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.UInt32],System.Object] ) -=-=-=-=-=-=-=-=- CObj(UInteger?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { Convert( Parameter( x type: System.Nullable`1[System.UInt32] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.UInt32],System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_UInteger) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { ConvertChecked( Parameter( x type: E_UInteger ) type: System.Byte ) } return type: System.Byte type: System.Func`2[E_UInteger,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_UInteger) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { ConvertChecked( Parameter( x type: E_UInteger ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[E_UInteger,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(E_UInteger) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { ConvertChecked( Parameter( x type: E_UInteger ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[E_UInteger,System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(E_UInteger, E_UInteger) -> E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { Parameter( x type: E_UInteger ) } return type: E_UInteger type: System.Func`2[E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- CLng(E_UInteger) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { ConvertChecked( Parameter( x type: E_UInteger ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[E_UInteger,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_UInteger) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { Convert( ConvertChecked( Parameter( x type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[E_UInteger,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_UInteger) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { Convert( Parameter( x type: E_UInteger ) type: System.Single ) } return type: System.Single type: System.Func`2[E_UInteger,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_UInteger) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { Convert( Parameter( x type: E_UInteger ) type: System.Double ) } return type: System.Double type: System.Func`2[E_UInteger,System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_UInteger) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { Convert( ConvertChecked( Parameter( x type: E_UInteger ) type: System.UInt32 ) method: System.Decimal op_Implicit(UInt32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[E_UInteger,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_UInteger) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { Convert( ConvertChecked( Parameter( x type: E_UInteger ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[E_UInteger,System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_UInteger, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { TypeAs( Parameter( x type: E_UInteger ) type: System.Object ) } return type: System.Object type: System.Func`2[E_UInteger,System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_UInteger) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { Convert( Parameter( x type: E_UInteger ) type: System.Object ) } return type: System.Object type: System.Func`2[E_UInteger,System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_UInteger?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[E_UInteger],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_UInteger?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[E_UInteger],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(E_UInteger?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[E_UInteger],System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(E_UInteger?, E_UInteger?) -> E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { Parameter( x type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`2[System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- CLng(E_UInteger?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[E_UInteger],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_UInteger?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[E_UInteger],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_UInteger?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[E_UInteger],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_UInteger?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[E_UInteger],System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_UInteger?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.UInt32 ) method: System.Decimal op_Implicit(UInt32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[E_UInteger],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_UInteger?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_UInteger],System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_UInteger?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { TypeAs( Parameter( x type: System.Nullable`1[E_UInteger] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_UInteger],System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_UInteger?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_UInteger],System.Object] ) -=-=-=-=-=-=-=-=- CByte(Long) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { ConvertChecked( Parameter( x type: System.Int64 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Int64,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Long) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { ConvertChecked( Parameter( x type: System.Int64 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Int64,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Long) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { ConvertChecked( Parameter( x type: System.Int64 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Int64,System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(Long, Long) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Parameter( x type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- CLng(Long) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Parameter( x type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Long) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Convert( Parameter( x type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Int64,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Long) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Convert( Parameter( x type: System.Int64 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Int64,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Long) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Convert( Parameter( x type: System.Int64 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Int64,System.Double] ) -=-=-=-=-=-=-=-=- CDec(Long) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Convert( Parameter( x type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Int64,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Long) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Convert( Parameter( x type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Int64,System.String] ) -=-=-=-=-=-=-=-=- TryCast(Long, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { TypeAs( Parameter( x type: System.Int64 ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Int64,System.Object] ) -=-=-=-=-=-=-=-=- CObj(Long) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Convert( Parameter( x type: System.Int64 ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Int64,System.Object] ) -=-=-=-=-=-=-=-=- CByte(Long?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.Int64],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Long?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.Int64],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Long?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.Int64],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Long?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { ConvertChecked( Parameter( x type: System.Nullable`1[System.Int64] ) Lifted type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.Int64],System.Int64] ) -=-=-=-=-=-=-=-=- DirectCast(Long?, Long?) -> Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { Parameter( x type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`2[System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- CBool(Long?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.Int64],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Long?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.Int64],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Long?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.Int64],System.Double] ) -=-=-=-=-=-=-=-=- CDec(Long?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.Int64],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Long?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Int64],System.String] ) -=-=-=-=-=-=-=-=- TryCast(Long?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.Int64] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Int64],System.Object] ) -=-=-=-=-=-=-=-=- CObj(Long?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { Convert( Parameter( x type: System.Nullable`1[System.Int64] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Int64],System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_Long) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { ConvertChecked( Parameter( x type: E_Long ) type: System.Byte ) } return type: System.Byte type: System.Func`2[E_Long,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_Long) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { ConvertChecked( Parameter( x type: E_Long ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[E_Long,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(E_Long) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { ConvertChecked( Parameter( x type: E_Long ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[E_Long,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(E_Long) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { ConvertChecked( Parameter( x type: E_Long ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[E_Long,System.Int64] ) -=-=-=-=-=-=-=-=- DirectCast(E_Long, E_Long) -> E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { Parameter( x type: E_Long ) } return type: E_Long type: System.Func`2[E_Long,E_Long] ) -=-=-=-=-=-=-=-=- CBool(E_Long) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { Convert( ConvertChecked( Parameter( x type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[E_Long,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_Long) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { Convert( Parameter( x type: E_Long ) type: System.Single ) } return type: System.Single type: System.Func`2[E_Long,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_Long) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { Convert( Parameter( x type: E_Long ) type: System.Double ) } return type: System.Double type: System.Func`2[E_Long,System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_Long) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { Convert( ConvertChecked( Parameter( x type: E_Long ) type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[E_Long,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_Long) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { Convert( ConvertChecked( Parameter( x type: E_Long ) type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[E_Long,System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_Long, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { TypeAs( Parameter( x type: E_Long ) type: System.Object ) } return type: System.Object type: System.Func`2[E_Long,System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_Long) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { Convert( Parameter( x type: E_Long ) type: System.Object ) } return type: System.Object type: System.Func`2[E_Long,System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_Long?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[E_Long],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_Long?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[E_Long],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(E_Long?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[E_Long],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(E_Long?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[E_Long],System.Int64] ) -=-=-=-=-=-=-=-=- DirectCast(E_Long?, E_Long?) -> E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { Parameter( x type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`2[System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- CBool(E_Long?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[E_Long],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_Long?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[E_Long],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_Long?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[E_Long],System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_Long?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[E_Long],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_Long?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Long],System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_Long?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { TypeAs( Parameter( x type: System.Nullable`1[E_Long] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_Long],System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_Long?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_Long],System.Object] ) -=-=-=-=-=-=-=-=- CByte(Boolean) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Convert( Negate( Convert( Parameter( x type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Boolean,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Boolean) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Negate( ConvertChecked( Parameter( x type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Boolean,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Boolean) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Negate( ConvertChecked( Parameter( x type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Boolean,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Boolean) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Negate( ConvertChecked( Parameter( x type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Boolean,System.Int64] ) -=-=-=-=-=-=-=-=- DirectCast(Boolean, Boolean) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Parameter( x type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- CBool(Boolean) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Parameter( x type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Boolean) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Negate( Convert( Parameter( x type: System.Boolean ) type: System.Single ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Boolean,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Boolean) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Negate( Convert( Parameter( x type: System.Boolean ) type: System.Double ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Boolean,System.Double] ) -=-=-=-=-=-=-=-=- CDec(Boolean) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Convert( Parameter( x type: System.Boolean ) method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Boolean,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Boolean) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Convert( Parameter( x type: System.Boolean ) method: System.String ToString(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Boolean,System.String] ) -=-=-=-=-=-=-=-=- TryCast(Boolean, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { TypeAs( Parameter( x type: System.Boolean ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Boolean,System.Object] ) -=-=-=-=-=-=-=-=- CObj(Boolean) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Convert( Parameter( x type: System.Boolean ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Boolean,System.Object] ) -=-=-=-=-=-=-=-=- CByte(Boolean?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Convert( Negate( Convert( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.Boolean],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Boolean?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Negate( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.Boolean],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Boolean?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Negate( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.Boolean],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Boolean?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Negate( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.Boolean],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Boolean?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) Lifted type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.Boolean],System.Boolean] ) -=-=-=-=-=-=-=-=- DirectCast(Boolean?, Boolean?) -> Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Parameter( x type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`2[System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- CSng(Boolean?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Negate( Convert( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Single ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.Boolean],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Boolean?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Negate( Convert( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Double ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.Boolean],System.Double] ) -=-=-=-=-=-=-=-=- CDec(Boolean?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.Boolean],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Boolean?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) method: System.String ToString(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Boolean],System.String] ) -=-=-=-=-=-=-=-=- TryCast(Boolean?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.Boolean] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Boolean],System.Object] ) -=-=-=-=-=-=-=-=- CObj(Boolean?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Boolean],System.Object] ) -=-=-=-=-=-=-=-=- CByte(Single) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { ConvertChecked( Parameter( x type: System.Single ) method: Byte ToByte(Single) in System.Convert type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Single,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Single) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { ConvertChecked( Parameter( x type: System.Single ) method: Int16 ToInt16(Single) in System.Convert type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Single,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Single) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { ConvertChecked( Parameter( x type: System.Single ) method: Int32 ToInt32(Single) in System.Convert type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Single,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Single) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { ConvertChecked( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Single,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Single) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { Convert( Parameter( x type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Single,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Single) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { Convert( Parameter( x type: System.Single ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Single,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Single) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { Convert( Parameter( x type: System.Single ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Single,System.Double] ) -=-=-=-=-=-=-=-=- CDec(Single) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { Convert( Parameter( x type: System.Single ) method: System.Decimal op_Explicit(Single) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Single,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Single) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { Convert( Parameter( x type: System.Single ) method: System.String ToString(Single) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Single,System.String] ) -=-=-=-=-=-=-=-=- TryCast(Single, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { TypeAs( Parameter( x type: System.Single ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Single,System.Object] ) -=-=-=-=-=-=-=-=- CObj(Single) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { Convert( Parameter( x type: System.Single ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Single,System.Object] ) -=-=-=-=-=-=-=-=- CByte(Single?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Single] ) method: Single op_Explicit(System.Nullable`1[System.Single]) in System.Nullable`1[System.Single] type: System.Single ) method: Byte ToByte(Single) in System.Convert type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.Single],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Single?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Single] ) method: Single op_Explicit(System.Nullable`1[System.Single]) in System.Nullable`1[System.Single] type: System.Single ) method: Int16 ToInt16(Single) in System.Convert type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.Single],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Single?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Single] ) method: Single op_Explicit(System.Nullable`1[System.Single]) in System.Nullable`1[System.Single] type: System.Single ) method: Int32 ToInt32(Single) in System.Convert type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.Single],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Single?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Single] ) method: Single op_Explicit(System.Nullable`1[System.Single]) in System.Nullable`1[System.Single] type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.Single],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Single?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Single] ) method: Single op_Explicit(System.Nullable`1[System.Single]) in System.Nullable`1[System.Single] type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.Single],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Single?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { Convert( Parameter( x type: System.Nullable`1[System.Single] ) Lifted type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.Single],System.Single] ) -=-=-=-=-=-=-=-=- DirectCast(Single?, Single?) -> Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { Parameter( x type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`2[System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- CDbl(Single?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Single] ) method: Single op_Explicit(System.Nullable`1[System.Single]) in System.Nullable`1[System.Single] type: System.Single ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.Single],System.Double] ) -=-=-=-=-=-=-=-=- CDec(Single?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Single] ) method: Single op_Explicit(System.Nullable`1[System.Single]) in System.Nullable`1[System.Single] type: System.Single ) method: System.Decimal op_Explicit(Single) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.Single],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Single?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Single] ) method: Single op_Explicit(System.Nullable`1[System.Single]) in System.Nullable`1[System.Single] type: System.Single ) method: System.String ToString(Single) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Single],System.String] ) -=-=-=-=-=-=-=-=- TryCast(Single?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.Single] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Single],System.Object] ) -=-=-=-=-=-=-=-=- CObj(Single?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { Convert( Parameter( x type: System.Nullable`1[System.Single] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Single],System.Object] ) -=-=-=-=-=-=-=-=- CByte(Double) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { ConvertChecked( Parameter( x type: System.Double ) method: Byte ToByte(Double) in System.Convert type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Double,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Double) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { ConvertChecked( Parameter( x type: System.Double ) method: Int16 ToInt16(Double) in System.Convert type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Double,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Double) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { ConvertChecked( Parameter( x type: System.Double ) method: Int32 ToInt32(Double) in System.Convert type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Double,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Double) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { ConvertChecked( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Double,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Double) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { Convert( Parameter( x type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Double,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Double) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { Convert( Parameter( x type: System.Double ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Double,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Double) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { Convert( Parameter( x type: System.Double ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Double,System.Double] ) -=-=-=-=-=-=-=-=- CDec(Double) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { Convert( Parameter( x type: System.Double ) method: System.Decimal op_Explicit(Double) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Double,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Double) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { Convert( Parameter( x type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Double,System.String] ) -=-=-=-=-=-=-=-=- TryCast(Double, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { TypeAs( Parameter( x type: System.Double ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Double,System.Object] ) -=-=-=-=-=-=-=-=- CObj(Double) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { Convert( Parameter( x type: System.Double ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Double,System.Object] ) -=-=-=-=-=-=-=-=- CByte(Double?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: Byte ToByte(Double) in System.Convert type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.Double],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Double?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: Int16 ToInt16(Double) in System.Convert type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.Double],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Double?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: Int32 ToInt32(Double) in System.Convert type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.Double],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Double?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.Double],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Double?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.Double],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Double?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.Double],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Double?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { Convert( Parameter( x type: System.Nullable`1[System.Double] ) Lifted type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.Double],System.Double] ) -=-=-=-=-=-=-=-=- DirectCast(Double?, Double?) -> Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { Parameter( x type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`2[System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- CDec(Double?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.Decimal op_Explicit(Double) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.Double],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Double?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Double],System.String] ) -=-=-=-=-=-=-=-=- TryCast(Double?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.Double] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Double],System.Object] ) -=-=-=-=-=-=-=-=- CObj(Double?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { Convert( Parameter( x type: System.Nullable`1[System.Double] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Double],System.Object] ) -=-=-=-=-=-=-=-=- CByte(Decimal) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { ConvertChecked( Parameter( x type: System.Decimal ) method: Byte op_Explicit(System.Decimal) in System.Decimal type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Decimal,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Decimal) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { ConvertChecked( Parameter( x type: System.Decimal ) method: Int16 op_Explicit(System.Decimal) in System.Decimal type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Decimal,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Decimal) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { ConvertChecked( Parameter( x type: System.Decimal ) method: Int32 op_Explicit(System.Decimal) in System.Decimal type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Decimal,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Decimal) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { ConvertChecked( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Decimal,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Decimal) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { Convert( Parameter( x type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Decimal,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Decimal) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { Convert( Parameter( x type: System.Decimal ) method: Single op_Explicit(System.Decimal) in System.Decimal type: System.Single ) } return type: System.Single type: System.Func`2[System.Decimal,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Decimal) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { Convert( Parameter( x type: System.Decimal ) method: Double op_Explicit(System.Decimal) in System.Decimal type: System.Double ) } return type: System.Double type: System.Func`2[System.Decimal,System.Double] ) -=-=-=-=-=-=-=-=- DirectCast(Decimal, Decimal) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { Parameter( x type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- CDec(Decimal) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { Parameter( x type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Decimal) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { Convert( Parameter( x type: System.Decimal ) method: System.String ToString(System.Decimal) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Decimal,System.String] ) -=-=-=-=-=-=-=-=- TryCast(Decimal, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { TypeAs( Parameter( x type: System.Decimal ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Decimal,System.Object] ) -=-=-=-=-=-=-=-=- CObj(Decimal) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { Convert( Parameter( x type: System.Decimal ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Decimal,System.Object] ) -=-=-=-=-=-=-=-=- CByte(Decimal?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) method: System.Decimal op_Explicit(System.Nullable`1[System.Decimal]) in System.Nullable`1[System.Decimal] type: System.Decimal ) method: Byte op_Explicit(System.Decimal) in System.Decimal type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.Decimal],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Decimal?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) method: System.Decimal op_Explicit(System.Nullable`1[System.Decimal]) in System.Nullable`1[System.Decimal] type: System.Decimal ) method: Int16 op_Explicit(System.Decimal) in System.Decimal type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.Decimal],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Decimal?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) method: System.Decimal op_Explicit(System.Nullable`1[System.Decimal]) in System.Nullable`1[System.Decimal] type: System.Decimal ) method: Int32 op_Explicit(System.Decimal) in System.Decimal type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.Decimal],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Decimal?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) method: System.Decimal op_Explicit(System.Nullable`1[System.Decimal]) in System.Nullable`1[System.Decimal] type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.Decimal],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Decimal?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) method: System.Decimal op_Explicit(System.Nullable`1[System.Decimal]) in System.Nullable`1[System.Decimal] type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.Decimal],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Decimal?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) method: System.Decimal op_Explicit(System.Nullable`1[System.Decimal]) in System.Nullable`1[System.Decimal] type: System.Decimal ) method: Single op_Explicit(System.Decimal) in System.Decimal type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.Decimal],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Decimal?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) method: System.Decimal op_Explicit(System.Nullable`1[System.Decimal]) in System.Nullable`1[System.Decimal] type: System.Decimal ) method: Double op_Explicit(System.Decimal) in System.Decimal type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.Decimal],System.Double] ) -=-=-=-=-=-=-=-=- CDec(Decimal?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.Decimal],System.Decimal] ) -=-=-=-=-=-=-=-=- DirectCast(Decimal?, Decimal?) -> Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { Parameter( x type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`2[System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- CStr(Decimal?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) method: System.Decimal op_Explicit(System.Nullable`1[System.Decimal]) in System.Nullable`1[System.Decimal] type: System.Decimal ) method: System.String ToString(System.Decimal) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Decimal],System.String] ) -=-=-=-=-=-=-=-=- TryCast(Decimal?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.Decimal] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Decimal],System.Object] ) -=-=-=-=-=-=-=-=- CObj(Decimal?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Decimal],System.Object] ) -=-=-=-=-=-=-=-=- DirectCast(Date, Date) -> Date -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.DateTime ) body { Parameter( x type: System.DateTime ) } return type: System.DateTime type: System.Func`2[System.DateTime,System.DateTime] ) -=-=-=-=-=-=-=-=- CStr(Date) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.DateTime ) body { Convert( Parameter( x type: System.DateTime ) method: System.String ToString(System.DateTime) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.DateTime,System.String] ) -=-=-=-=-=-=-=-=- TryCast(Date, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.DateTime ) body { TypeAs( Parameter( x type: System.DateTime ) type: System.Object ) } return type: System.Object type: System.Func`2[System.DateTime,System.Object] ) -=-=-=-=-=-=-=-=- CObj(Date) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.DateTime ) body { Convert( Parameter( x type: System.DateTime ) type: System.Object ) } return type: System.Object type: System.Func`2[System.DateTime,System.Object] ) -=-=-=-=-=-=-=-=- DirectCast(Date?, Date?) -> Date? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.DateTime] ) body { Parameter( x type: System.Nullable`1[System.DateTime] ) } return type: System.Nullable`1[System.DateTime] type: System.Func`2[System.Nullable`1[System.DateTime],System.Nullable`1[System.DateTime]] ) -=-=-=-=-=-=-=-=- CStr(Date?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.DateTime] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.DateTime] ) method: System.DateTime op_Explicit(System.Nullable`1[System.DateTime]) in System.Nullable`1[System.DateTime] type: System.DateTime ) method: System.String ToString(System.DateTime) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.DateTime],System.String] ) -=-=-=-=-=-=-=-=- TryCast(Date?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.DateTime] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.DateTime] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.DateTime],System.Object] ) -=-=-=-=-=-=-=-=- CObj(Date?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.DateTime] ) body { Convert( Parameter( x type: System.Nullable`1[System.DateTime] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.DateTime],System.Object] ) -=-=-=-=-=-=-=-=- CByte(String) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { ConvertChecked( Parameter( x type: System.String ) method: Byte ToByte(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Byte ) } return type: System.Byte type: System.Func`2[System.String,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(String) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { ConvertChecked( Parameter( x type: System.String ) method: Int16 ToShort(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.String,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(String) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { ConvertChecked( Parameter( x type: System.String ) method: Int32 ToInteger(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.String,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(String) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { ConvertChecked( Parameter( x type: System.String ) method: Int64 ToLong(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.String,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(String) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Parameter( x type: System.String ) method: Boolean ToBoolean(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.String,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(String) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Parameter( x type: System.String ) method: Single ToSingle(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Single ) } return type: System.Single type: System.Func`2[System.String,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(String) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) } return type: System.Double type: System.Func`2[System.String,System.Double] ) -=-=-=-=-=-=-=-=- CDec(String) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Parameter( x type: System.String ) method: System.Decimal ToDecimal(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.String,System.Decimal] ) -=-=-=-=-=-=-=-=- CDate(String) -> Date -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Parameter( x type: System.String ) method: System.DateTime ToDate(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.DateTime ) } return type: System.DateTime type: System.Func`2[System.String,System.DateTime] ) -=-=-=-=-=-=-=-=- DirectCast(String, String) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Parameter( x type: System.String ) } return type: System.String type: System.Func`2[System.String,System.String] ) -=-=-=-=-=-=-=-=- CStr(String) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Parameter( x type: System.String ) } return type: System.String type: System.Func`2[System.String,System.String] ) -=-=-=-=-=-=-=-=- DirectCast(String, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Parameter( x type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`2[System.String,System.Object] ) -=-=-=-=-=-=-=-=- TryCast(String, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Parameter( x type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`2[System.String,System.Object] ) -=-=-=-=-=-=-=-=- CObj(String) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Parameter( x type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`2[System.String,System.Object] ) -=-=-=-=-=-=-=-=- DirectCast(Object, SByte) -> SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.SByte ) } return type: System.SByte type: System.Func`2[System.Object,System.SByte] ) -=-=-=-=-=-=-=-=- DirectCast(Object, SByte?) -> SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`2[System.Object,System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_SByte) -> E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: E_SByte ) } return type: E_SByte type: System.Func`2[System.Object,E_SByte] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_SByte?) -> E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`2[System.Object,System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Byte) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Object,System.Byte] ) -=-=-=-=-=-=-=-=- CByte(Object) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { ConvertChecked( Parameter( x type: System.Object ) method: Byte ToByte(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Object,System.Byte] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Byte?) -> Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`2[System.Object,System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_Byte) -> E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: E_Byte ) } return type: E_Byte type: System.Func`2[System.Object,E_Byte] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_Byte?) -> E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`2[System.Object,System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Short) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Object,System.Int16] ) -=-=-=-=-=-=-=-=- CShort(Object) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { ConvertChecked( Parameter( x type: System.Object ) method: Int16 ToShort(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Object,System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Short?) -> Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`2[System.Object,System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_Short) -> E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: E_Short ) } return type: E_Short type: System.Func`2[System.Object,E_Short] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_Short?) -> E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`2[System.Object,System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, UShort) -> UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.UInt16 ) } return type: System.UInt16 type: System.Func`2[System.Object,System.UInt16] ) -=-=-=-=-=-=-=-=- DirectCast(Object, UShort?) -> UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`2[System.Object,System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_UShort) -> E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: E_UShort ) } return type: E_UShort type: System.Func`2[System.Object,E_UShort] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_UShort?) -> E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`2[System.Object,System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Integer) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Object,System.Int32] ) -=-=-=-=-=-=-=-=- CInt(Object) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { ConvertChecked( Parameter( x type: System.Object ) method: Int32 ToInteger(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Object,System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Integer?) -> Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`2[System.Object,System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_Integer) -> E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: E_Integer ) } return type: E_Integer type: System.Func`2[System.Object,E_Integer] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_Integer?) -> E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`2[System.Object,System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, UInteger) -> UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.UInt32 ) } return type: System.UInt32 type: System.Func`2[System.Object,System.UInt32] ) -=-=-=-=-=-=-=-=- DirectCast(Object, UInteger?) -> UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`2[System.Object,System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_UInteger) -> E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: E_UInteger ) } return type: E_UInteger type: System.Func`2[System.Object,E_UInteger] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_UInteger?) -> E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`2[System.Object,System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Long) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Object,System.Int64] ) -=-=-=-=-=-=-=-=- CLng(Object) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { ConvertChecked( Parameter( x type: System.Object ) method: Int64 ToLong(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Object,System.Int64] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Long?) -> Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`2[System.Object,System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_Long) -> E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: E_Long ) } return type: E_Long type: System.Func`2[System.Object,E_Long] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_Long?) -> E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`2[System.Object,System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Boolean) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Object,System.Boolean] ) -=-=-=-=-=-=-=-=- CBool(Object) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) method: Boolean ToBoolean(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Object,System.Boolean] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Boolean?) -> Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`2[System.Object,System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Single) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Object,System.Single] ) -=-=-=-=-=-=-=-=- CSng(Object) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) method: Single ToSingle(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Single ) } return type: System.Single type: System.Func`2[System.Object,System.Single] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Single?) -> Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`2[System.Object,System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Double) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Object,System.Double] ) -=-=-=-=-=-=-=-=- CDbl(Object) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) method: Double ToDouble(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) } return type: System.Double type: System.Func`2[System.Object,System.Double] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Double?) -> Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`2[System.Object,System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Decimal) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Object,System.Decimal] ) -=-=-=-=-=-=-=-=- CDec(Object) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) method: System.Decimal ToDecimal(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Object,System.Decimal] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Decimal?) -> Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`2[System.Object,System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Date) -> Date -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.DateTime ) } return type: System.DateTime type: System.Func`2[System.Object,System.DateTime] ) -=-=-=-=-=-=-=-=- CDate(Object) -> Date -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) method: System.DateTime ToDate(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.DateTime ) } return type: System.DateTime type: System.Func`2[System.Object,System.DateTime] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Date?) -> Date? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.DateTime] ) } return type: System.Nullable`1[System.DateTime] type: System.Func`2[System.Object,System.Nullable`1[System.DateTime]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, String) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.String ) } return type: System.String type: System.Func`2[System.Object,System.String] ) -=-=-=-=-=-=-=-=- CStr(Object) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) method: System.String ToString(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Object,System.String] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Parameter( x type: System.Object ) } return type: System.Object type: System.Func`2[System.Object,System.Object] ) -=-=-=-=-=-=-=-=- TryCast(Object, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Parameter( x type: System.Object ) } return type: System.Object type: System.Func`2[System.Object,System.Object] ) -=-=-=-=-=-=-=-=- CObj(Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Parameter( x type: System.Object ) } return type: System.Object type: System.Func`2[System.Object,System.Object] )
-=-=-=-=-=-=-=-=- DirectCast(SByte, SByte) -> SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { Parameter( x type: System.SByte ) } return type: System.SByte type: System.Func`2[System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- CByte(SByte) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { ConvertChecked( Parameter( x type: System.SByte ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.SByte,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(SByte) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { ConvertChecked( Parameter( x type: System.SByte ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.SByte,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(SByte) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.SByte,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(SByte) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { ConvertChecked( Parameter( x type: System.SByte ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.SByte,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(SByte) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { Convert( ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.SByte,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(SByte) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { Convert( Parameter( x type: System.SByte ) type: System.Single ) } return type: System.Single type: System.Func`2[System.SByte,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(SByte) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { Convert( Parameter( x type: System.SByte ) type: System.Double ) } return type: System.Double type: System.Func`2[System.SByte,System.Double] ) -=-=-=-=-=-=-=-=- CDec(SByte) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { Convert( ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.SByte,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(SByte) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { Convert( ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.SByte,System.String] ) -=-=-=-=-=-=-=-=- TryCast(SByte, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { TypeAs( Parameter( x type: System.SByte ) type: System.Object ) } return type: System.Object type: System.Func`2[System.SByte,System.Object] ) -=-=-=-=-=-=-=-=- CObj(SByte) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { Convert( Parameter( x type: System.SByte ) type: System.Object ) } return type: System.Object type: System.Func`2[System.SByte,System.Object] ) -=-=-=-=-=-=-=-=- DirectCast(SByte?, SByte?) -> SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { Parameter( x type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`2[System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- CByte(SByte?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.SByte],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(SByte?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.SByte],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(SByte?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.SByte],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(SByte?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.SByte],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(SByte?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.SByte],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(SByte?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.SByte],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(SByte?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.SByte],System.Double] ) -=-=-=-=-=-=-=-=- CDec(SByte?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.SByte],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(SByte?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.SByte],System.String] ) -=-=-=-=-=-=-=-=- TryCast(SByte?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.SByte] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.SByte],System.Object] ) -=-=-=-=-=-=-=-=- CObj(SByte?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { Convert( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.SByte],System.Object] ) -=-=-=-=-=-=-=-=- DirectCast(E_SByte, E_SByte) -> E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { Parameter( x type: E_SByte ) } return type: E_SByte type: System.Func`2[E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- CByte(E_SByte) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { ConvertChecked( Parameter( x type: E_SByte ) type: System.Byte ) } return type: System.Byte type: System.Func`2[E_SByte,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_SByte) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { ConvertChecked( Parameter( x type: E_SByte ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[E_SByte,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(E_SByte) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { ConvertChecked( Parameter( x type: E_SByte ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[E_SByte,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(E_SByte) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { ConvertChecked( Parameter( x type: E_SByte ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[E_SByte,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_SByte) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { Convert( ConvertChecked( Parameter( x type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[E_SByte,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_SByte) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { Convert( Parameter( x type: E_SByte ) type: System.Single ) } return type: System.Single type: System.Func`2[E_SByte,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_SByte) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { Convert( Parameter( x type: E_SByte ) type: System.Double ) } return type: System.Double type: System.Func`2[E_SByte,System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_SByte) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { Convert( ConvertChecked( Parameter( x type: E_SByte ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[E_SByte,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_SByte) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { Convert( ConvertChecked( Parameter( x type: E_SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[E_SByte,System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_SByte, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { TypeAs( Parameter( x type: E_SByte ) type: System.Object ) } return type: System.Object type: System.Func`2[E_SByte,System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_SByte) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { Convert( Parameter( x type: E_SByte ) type: System.Object ) } return type: System.Object type: System.Func`2[E_SByte,System.Object] ) -=-=-=-=-=-=-=-=- DirectCast(E_SByte?, E_SByte?) -> E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { Parameter( x type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`2[System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- CByte(E_SByte?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[E_SByte],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_SByte?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[E_SByte],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(E_SByte?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[E_SByte],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(E_SByte?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[E_SByte],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_SByte?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[E_SByte],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_SByte?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[E_SByte],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_SByte?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[E_SByte],System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_SByte?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[E_SByte],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_SByte?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_SByte],System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_SByte?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { TypeAs( Parameter( x type: System.Nullable`1[E_SByte] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_SByte],System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_SByte?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_SByte],System.Object] ) -=-=-=-=-=-=-=-=- DirectCast(Byte, Byte) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Parameter( x type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- CByte(Byte) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Parameter( x type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Byte) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { ConvertChecked( Parameter( x type: System.Byte ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Byte,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Byte) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { ConvertChecked( Parameter( x type: System.Byte ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Byte,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Byte) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { ConvertChecked( Parameter( x type: System.Byte ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Byte,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Byte) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Convert( ConvertChecked( Parameter( x type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Byte,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Byte) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Convert( Parameter( x type: System.Byte ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Byte,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Byte) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Convert( Parameter( x type: System.Byte ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Byte,System.Double] ) -=-=-=-=-=-=-=-=- CDec(Byte) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Convert( ConvertChecked( Parameter( x type: System.Byte ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Byte,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Byte) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Convert( Parameter( x type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Byte,System.String] ) -=-=-=-=-=-=-=-=- TryCast(Byte, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { TypeAs( Parameter( x type: System.Byte ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Byte,System.Object] ) -=-=-=-=-=-=-=-=- CObj(Byte) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Convert( Parameter( x type: System.Byte ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Byte,System.Object] ) -=-=-=-=-=-=-=-=- CByte(Byte?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.Byte],System.Byte] ) -=-=-=-=-=-=-=-=- DirectCast(Byte?, Byte?) -> Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { Parameter( x type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`2[System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- CShort(Byte?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) method: Byte op_Explicit(System.Nullable`1[System.Byte]) in System.Nullable`1[System.Byte] type: System.Byte ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.Byte],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Byte?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) method: Byte op_Explicit(System.Nullable`1[System.Byte]) in System.Nullable`1[System.Byte] type: System.Byte ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.Byte],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Byte?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) method: Byte op_Explicit(System.Nullable`1[System.Byte]) in System.Nullable`1[System.Byte] type: System.Byte ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.Byte],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Byte?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) method: Byte op_Explicit(System.Nullable`1[System.Byte]) in System.Nullable`1[System.Byte] type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.Byte],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Byte?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) method: Byte op_Explicit(System.Nullable`1[System.Byte]) in System.Nullable`1[System.Byte] type: System.Byte ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.Byte],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Byte?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) method: Byte op_Explicit(System.Nullable`1[System.Byte]) in System.Nullable`1[System.Byte] type: System.Byte ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.Byte],System.Double] ) -=-=-=-=-=-=-=-=- CDec(Byte?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) method: Byte op_Explicit(System.Nullable`1[System.Byte]) in System.Nullable`1[System.Byte] type: System.Byte ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.Byte],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Byte?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Byte] ) method: Byte op_Explicit(System.Nullable`1[System.Byte]) in System.Nullable`1[System.Byte] type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Byte],System.String] ) -=-=-=-=-=-=-=-=- TryCast(Byte?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.Byte] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Byte],System.Object] ) -=-=-=-=-=-=-=-=- CObj(Byte?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { Convert( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Byte],System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_Byte) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { ConvertChecked( Parameter( x type: E_Byte ) type: System.Byte ) } return type: System.Byte type: System.Func`2[E_Byte,System.Byte] ) -=-=-=-=-=-=-=-=- DirectCast(E_Byte, E_Byte) -> E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { Parameter( x type: E_Byte ) } return type: E_Byte type: System.Func`2[E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- CShort(E_Byte) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { ConvertChecked( Parameter( x type: E_Byte ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[E_Byte,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(E_Byte) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { ConvertChecked( Parameter( x type: E_Byte ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[E_Byte,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(E_Byte) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { ConvertChecked( Parameter( x type: E_Byte ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[E_Byte,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_Byte) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { Convert( ConvertChecked( Parameter( x type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[E_Byte,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_Byte) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { Convert( Parameter( x type: E_Byte ) type: System.Single ) } return type: System.Single type: System.Func`2[E_Byte,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_Byte) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { Convert( Parameter( x type: E_Byte ) type: System.Double ) } return type: System.Double type: System.Func`2[E_Byte,System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_Byte) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { Convert( ConvertChecked( Parameter( x type: E_Byte ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[E_Byte,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_Byte) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { Convert( ConvertChecked( Parameter( x type: E_Byte ) type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[E_Byte,System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_Byte, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { TypeAs( Parameter( x type: E_Byte ) type: System.Object ) } return type: System.Object type: System.Func`2[E_Byte,System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_Byte) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { Convert( Parameter( x type: E_Byte ) type: System.Object ) } return type: System.Object type: System.Func`2[E_Byte,System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_Byte?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[E_Byte],System.Byte] ) -=-=-=-=-=-=-=-=- DirectCast(E_Byte?, E_Byte?) -> E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { Parameter( x type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`2[System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- CShort(E_Byte?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[E_Byte],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(E_Byte?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[E_Byte],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(E_Byte?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[E_Byte],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_Byte?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[E_Byte],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_Byte?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[E_Byte],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_Byte?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[E_Byte],System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_Byte?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[E_Byte],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_Byte?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Byte],System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_Byte?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { TypeAs( Parameter( x type: System.Nullable`1[E_Byte] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_Byte],System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_Byte?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_Byte],System.Object] ) -=-=-=-=-=-=-=-=- CByte(Short) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { ConvertChecked( Parameter( x type: System.Int16 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Int16,System.Byte] ) -=-=-=-=-=-=-=-=- DirectCast(Short, Short) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Parameter( x type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- CShort(Short) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Parameter( x type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Short) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { ConvertChecked( Parameter( x type: System.Int16 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Int16,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Short) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { ConvertChecked( Parameter( x type: System.Int16 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Int16,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Short) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Convert( ConvertChecked( Parameter( x type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Int16,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Short) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Convert( Parameter( x type: System.Int16 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Int16,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Short) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Convert( Parameter( x type: System.Int16 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Int16,System.Double] ) -=-=-=-=-=-=-=-=- CDec(Short) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Convert( ConvertChecked( Parameter( x type: System.Int16 ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Int16,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Short) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Convert( ConvertChecked( Parameter( x type: System.Int16 ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Int16,System.String] ) -=-=-=-=-=-=-=-=- TryCast(Short, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { TypeAs( Parameter( x type: System.Int16 ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Int16,System.Object] ) -=-=-=-=-=-=-=-=- CObj(Short) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Convert( Parameter( x type: System.Int16 ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Int16,System.Object] ) -=-=-=-=-=-=-=-=- CByte(Short?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int16] ) method: Int16 op_Explicit(System.Nullable`1[System.Int16]) in System.Nullable`1[System.Int16] type: System.Int16 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.Int16],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Short?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { ConvertChecked( Parameter( x type: System.Nullable`1[System.Int16] ) Lifted type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.Int16],System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(Short?, Short?) -> Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { Parameter( x type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`2[System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- CInt(Short?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int16] ) method: Int16 op_Explicit(System.Nullable`1[System.Int16]) in System.Nullable`1[System.Int16] type: System.Int16 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.Int16],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Short?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int16] ) method: Int16 op_Explicit(System.Nullable`1[System.Int16]) in System.Nullable`1[System.Int16] type: System.Int16 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.Int16],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Short?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int16] ) method: Int16 op_Explicit(System.Nullable`1[System.Int16]) in System.Nullable`1[System.Int16] type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.Int16],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Short?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int16] ) method: Int16 op_Explicit(System.Nullable`1[System.Int16]) in System.Nullable`1[System.Int16] type: System.Int16 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.Int16],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Short?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int16] ) method: Int16 op_Explicit(System.Nullable`1[System.Int16]) in System.Nullable`1[System.Int16] type: System.Int16 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.Int16],System.Double] ) -=-=-=-=-=-=-=-=- CDec(Short?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int16] ) method: Int16 op_Explicit(System.Nullable`1[System.Int16]) in System.Nullable`1[System.Int16] type: System.Int16 ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.Int16],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Short?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int16] ) method: Int16 op_Explicit(System.Nullable`1[System.Int16]) in System.Nullable`1[System.Int16] type: System.Int16 ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Int16],System.String] ) -=-=-=-=-=-=-=-=- TryCast(Short?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.Int16] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Int16],System.Object] ) -=-=-=-=-=-=-=-=- CObj(Short?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { Convert( Parameter( x type: System.Nullable`1[System.Int16] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Int16],System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_Short) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { ConvertChecked( Parameter( x type: E_Short ) type: System.Byte ) } return type: System.Byte type: System.Func`2[E_Short,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_Short) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { ConvertChecked( Parameter( x type: E_Short ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[E_Short,System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(E_Short, E_Short) -> E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { Parameter( x type: E_Short ) } return type: E_Short type: System.Func`2[E_Short,E_Short] ) -=-=-=-=-=-=-=-=- CInt(E_Short) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { ConvertChecked( Parameter( x type: E_Short ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[E_Short,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(E_Short) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { ConvertChecked( Parameter( x type: E_Short ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[E_Short,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_Short) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { Convert( ConvertChecked( Parameter( x type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[E_Short,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_Short) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { Convert( Parameter( x type: E_Short ) type: System.Single ) } return type: System.Single type: System.Func`2[E_Short,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_Short) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { Convert( Parameter( x type: E_Short ) type: System.Double ) } return type: System.Double type: System.Func`2[E_Short,System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_Short) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { Convert( ConvertChecked( Parameter( x type: E_Short ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[E_Short,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_Short) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { Convert( ConvertChecked( Parameter( x type: E_Short ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[E_Short,System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_Short, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { TypeAs( Parameter( x type: E_Short ) type: System.Object ) } return type: System.Object type: System.Func`2[E_Short,System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_Short) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { Convert( Parameter( x type: E_Short ) type: System.Object ) } return type: System.Object type: System.Func`2[E_Short,System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_Short?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[E_Short],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_Short?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[E_Short],System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(E_Short?, E_Short?) -> E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { Parameter( x type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`2[System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- CInt(E_Short?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[E_Short],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(E_Short?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[E_Short],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_Short?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[E_Short],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_Short?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[E_Short],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_Short?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[E_Short],System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_Short?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[E_Short],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_Short?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Short],System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_Short?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { TypeAs( Parameter( x type: System.Nullable`1[E_Short] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_Short],System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_Short?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_Short],System.Object] ) -=-=-=-=-=-=-=-=- CByte(UShort) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { ConvertChecked( Parameter( x type: System.UInt16 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.UInt16,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(UShort) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { ConvertChecked( Parameter( x type: System.UInt16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.UInt16,System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(UShort, UShort) -> UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { Parameter( x type: System.UInt16 ) } return type: System.UInt16 type: System.Func`2[System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- CInt(UShort) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { ConvertChecked( Parameter( x type: System.UInt16 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.UInt16,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(UShort) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { ConvertChecked( Parameter( x type: System.UInt16 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.UInt16,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(UShort) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { Convert( ConvertChecked( Parameter( x type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.UInt16,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(UShort) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { Convert( Parameter( x type: System.UInt16 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.UInt16,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(UShort) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { Convert( Parameter( x type: System.UInt16 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.UInt16,System.Double] ) -=-=-=-=-=-=-=-=- CDec(UShort) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { Convert( ConvertChecked( Parameter( x type: System.UInt16 ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.UInt16,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(UShort) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { Convert( ConvertChecked( Parameter( x type: System.UInt16 ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.UInt16,System.String] ) -=-=-=-=-=-=-=-=- TryCast(UShort, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { TypeAs( Parameter( x type: System.UInt16 ) type: System.Object ) } return type: System.Object type: System.Func`2[System.UInt16,System.Object] ) -=-=-=-=-=-=-=-=- CObj(UShort) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { Convert( Parameter( x type: System.UInt16 ) type: System.Object ) } return type: System.Object type: System.Func`2[System.UInt16,System.Object] ) -=-=-=-=-=-=-=-=- CByte(UShort?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.UInt16],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(UShort?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.UInt16],System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(UShort?, UShort?) -> UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { Parameter( x type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`2[System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- CInt(UShort?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.UInt16],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(UShort?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.UInt16],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(UShort?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.UInt16],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(UShort?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.UInt16],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(UShort?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.UInt16],System.Double] ) -=-=-=-=-=-=-=-=- CDec(UShort?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.UInt16],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(UShort?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.UInt16],System.String] ) -=-=-=-=-=-=-=-=- TryCast(UShort?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.UInt16] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.UInt16],System.Object] ) -=-=-=-=-=-=-=-=- CObj(UShort?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { Convert( Parameter( x type: System.Nullable`1[System.UInt16] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.UInt16],System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_UShort) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { ConvertChecked( Parameter( x type: E_UShort ) type: System.Byte ) } return type: System.Byte type: System.Func`2[E_UShort,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_UShort) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { ConvertChecked( Parameter( x type: E_UShort ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[E_UShort,System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(E_UShort, E_UShort) -> E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { Parameter( x type: E_UShort ) } return type: E_UShort type: System.Func`2[E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- CInt(E_UShort) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { ConvertChecked( Parameter( x type: E_UShort ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[E_UShort,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(E_UShort) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { ConvertChecked( Parameter( x type: E_UShort ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[E_UShort,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_UShort) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { Convert( ConvertChecked( Parameter( x type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[E_UShort,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_UShort) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { Convert( Parameter( x type: E_UShort ) type: System.Single ) } return type: System.Single type: System.Func`2[E_UShort,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_UShort) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { Convert( Parameter( x type: E_UShort ) type: System.Double ) } return type: System.Double type: System.Func`2[E_UShort,System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_UShort) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { Convert( ConvertChecked( Parameter( x type: E_UShort ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[E_UShort,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_UShort) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { Convert( ConvertChecked( Parameter( x type: E_UShort ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[E_UShort,System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_UShort, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { TypeAs( Parameter( x type: E_UShort ) type: System.Object ) } return type: System.Object type: System.Func`2[E_UShort,System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_UShort) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { Convert( Parameter( x type: E_UShort ) type: System.Object ) } return type: System.Object type: System.Func`2[E_UShort,System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_UShort?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[E_UShort],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_UShort?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[E_UShort],System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(E_UShort?, E_UShort?) -> E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { Parameter( x type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`2[System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- CInt(E_UShort?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[E_UShort],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(E_UShort?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[E_UShort],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_UShort?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[E_UShort],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_UShort?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[E_UShort],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_UShort?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[E_UShort],System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_UShort?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[E_UShort],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_UShort?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_UShort],System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_UShort?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { TypeAs( Parameter( x type: System.Nullable`1[E_UShort] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_UShort],System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_UShort?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_UShort],System.Object] ) -=-=-=-=-=-=-=-=- CByte(Integer) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { ConvertChecked( Parameter( x type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Int32,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Integer) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { ConvertChecked( Parameter( x type: System.Int32 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Int32,System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(Integer, Integer) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Parameter( x type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- CInt(Integer) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Parameter( x type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Integer) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { ConvertChecked( Parameter( x type: System.Int32 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Int32,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Integer) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Convert( Parameter( x type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Int32,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Integer) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Convert( Parameter( x type: System.Int32 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Int32,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Integer) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Convert( Parameter( x type: System.Int32 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Int32,System.Double] ) -=-=-=-=-=-=-=-=- CDec(Integer) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Convert( Parameter( x type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Int32,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Integer) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Convert( Parameter( x type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Int32,System.String] ) -=-=-=-=-=-=-=-=- TryCast(Integer, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { TypeAs( Parameter( x type: System.Int32 ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Int32,System.Object] ) -=-=-=-=-=-=-=-=- CObj(Integer) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Convert( Parameter( x type: System.Int32 ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Int32,System.Object] ) -=-=-=-=-=-=-=-=- CByte(Integer?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int32] ) method: Int32 op_Explicit(System.Nullable`1[System.Int32]) in System.Nullable`1[System.Int32] type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.Int32],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Integer?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int32] ) method: Int32 op_Explicit(System.Nullable`1[System.Int32]) in System.Nullable`1[System.Int32] type: System.Int32 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.Int32],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Integer?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { ConvertChecked( Parameter( x type: System.Nullable`1[System.Int32] ) Lifted type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.Int32],System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(Integer?, Integer?) -> Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { Parameter( x type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`2[System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- CLng(Integer?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int32] ) method: Int32 op_Explicit(System.Nullable`1[System.Int32]) in System.Nullable`1[System.Int32] type: System.Int32 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.Int32],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Integer?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int32] ) method: Int32 op_Explicit(System.Nullable`1[System.Int32]) in System.Nullable`1[System.Int32] type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.Int32],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Integer?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int32] ) method: Int32 op_Explicit(System.Nullable`1[System.Int32]) in System.Nullable`1[System.Int32] type: System.Int32 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.Int32],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Integer?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int32] ) method: Int32 op_Explicit(System.Nullable`1[System.Int32]) in System.Nullable`1[System.Int32] type: System.Int32 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.Int32],System.Double] ) -=-=-=-=-=-=-=-=- CDec(Integer?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int32] ) method: Int32 op_Explicit(System.Nullable`1[System.Int32]) in System.Nullable`1[System.Int32] type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.Int32],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Integer?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int32] ) method: Int32 op_Explicit(System.Nullable`1[System.Int32]) in System.Nullable`1[System.Int32] type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Int32],System.String] ) -=-=-=-=-=-=-=-=- TryCast(Integer?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.Int32] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Int32],System.Object] ) -=-=-=-=-=-=-=-=- CObj(Integer?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { Convert( Parameter( x type: System.Nullable`1[System.Int32] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Int32],System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_Integer) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { ConvertChecked( Parameter( x type: E_Integer ) type: System.Byte ) } return type: System.Byte type: System.Func`2[E_Integer,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_Integer) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { ConvertChecked( Parameter( x type: E_Integer ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[E_Integer,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(E_Integer) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { ConvertChecked( Parameter( x type: E_Integer ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[E_Integer,System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(E_Integer, E_Integer) -> E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { Parameter( x type: E_Integer ) } return type: E_Integer type: System.Func`2[E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- CLng(E_Integer) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { ConvertChecked( Parameter( x type: E_Integer ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[E_Integer,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_Integer) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { Convert( ConvertChecked( Parameter( x type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[E_Integer,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_Integer) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { Convert( Parameter( x type: E_Integer ) type: System.Single ) } return type: System.Single type: System.Func`2[E_Integer,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_Integer) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { Convert( Parameter( x type: E_Integer ) type: System.Double ) } return type: System.Double type: System.Func`2[E_Integer,System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_Integer) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { Convert( ConvertChecked( Parameter( x type: E_Integer ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[E_Integer,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_Integer) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { Convert( ConvertChecked( Parameter( x type: E_Integer ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[E_Integer,System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_Integer, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { TypeAs( Parameter( x type: E_Integer ) type: System.Object ) } return type: System.Object type: System.Func`2[E_Integer,System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_Integer) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { Convert( Parameter( x type: E_Integer ) type: System.Object ) } return type: System.Object type: System.Func`2[E_Integer,System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_Integer?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[E_Integer],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_Integer?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[E_Integer],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(E_Integer?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[E_Integer],System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(E_Integer?, E_Integer?) -> E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { Parameter( x type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`2[System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- CLng(E_Integer?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[E_Integer],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_Integer?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[E_Integer],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_Integer?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[E_Integer],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_Integer?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[E_Integer],System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_Integer?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Int32 ) method: System.Decimal op_Implicit(Int32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[E_Integer],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_Integer?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Integer],System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_Integer?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { TypeAs( Parameter( x type: System.Nullable`1[E_Integer] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_Integer],System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_Integer?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_Integer],System.Object] ) -=-=-=-=-=-=-=-=- CByte(UInteger) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { ConvertChecked( Parameter( x type: System.UInt32 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.UInt32,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(UInteger) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { ConvertChecked( Parameter( x type: System.UInt32 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.UInt32,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(UInteger) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { ConvertChecked( Parameter( x type: System.UInt32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.UInt32,System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(UInteger, UInteger) -> UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { Parameter( x type: System.UInt32 ) } return type: System.UInt32 type: System.Func`2[System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- CLng(UInteger) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { ConvertChecked( Parameter( x type: System.UInt32 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.UInt32,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(UInteger) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { Convert( Parameter( x type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.UInt32,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(UInteger) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { Convert( Parameter( x type: System.UInt32 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.UInt32,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(UInteger) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { Convert( Parameter( x type: System.UInt32 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.UInt32,System.Double] ) -=-=-=-=-=-=-=-=- CDec(UInteger) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { Convert( Parameter( x type: System.UInt32 ) method: System.Decimal op_Implicit(UInt32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.UInt32,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(UInteger) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { Convert( Parameter( x type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.UInt32,System.String] ) -=-=-=-=-=-=-=-=- TryCast(UInteger, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { TypeAs( Parameter( x type: System.UInt32 ) type: System.Object ) } return type: System.Object type: System.Func`2[System.UInt32,System.Object] ) -=-=-=-=-=-=-=-=- CObj(UInteger) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { Convert( Parameter( x type: System.UInt32 ) type: System.Object ) } return type: System.Object type: System.Func`2[System.UInt32,System.Object] ) -=-=-=-=-=-=-=-=- CByte(UInteger?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.UInt32],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(UInteger?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.UInt32],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(UInteger?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.UInt32],System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(UInteger?, UInteger?) -> UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { Parameter( x type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`2[System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- CLng(UInteger?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.UInt32],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(UInteger?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.UInt32],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(UInteger?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.UInt32],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(UInteger?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.UInt32],System.Double] ) -=-=-=-=-=-=-=-=- CDec(UInteger?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) method: System.Decimal op_Implicit(UInt32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.UInt32],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(UInteger?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.UInt32],System.String] ) -=-=-=-=-=-=-=-=- TryCast(UInteger?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.UInt32] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.UInt32],System.Object] ) -=-=-=-=-=-=-=-=- CObj(UInteger?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { Convert( Parameter( x type: System.Nullable`1[System.UInt32] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.UInt32],System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_UInteger) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { ConvertChecked( Parameter( x type: E_UInteger ) type: System.Byte ) } return type: System.Byte type: System.Func`2[E_UInteger,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_UInteger) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { ConvertChecked( Parameter( x type: E_UInteger ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[E_UInteger,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(E_UInteger) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { ConvertChecked( Parameter( x type: E_UInteger ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[E_UInteger,System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(E_UInteger, E_UInteger) -> E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { Parameter( x type: E_UInteger ) } return type: E_UInteger type: System.Func`2[E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- CLng(E_UInteger) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { ConvertChecked( Parameter( x type: E_UInteger ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[E_UInteger,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_UInteger) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { Convert( ConvertChecked( Parameter( x type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[E_UInteger,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_UInteger) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { Convert( Parameter( x type: E_UInteger ) type: System.Single ) } return type: System.Single type: System.Func`2[E_UInteger,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_UInteger) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { Convert( Parameter( x type: E_UInteger ) type: System.Double ) } return type: System.Double type: System.Func`2[E_UInteger,System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_UInteger) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { Convert( ConvertChecked( Parameter( x type: E_UInteger ) type: System.UInt32 ) method: System.Decimal op_Implicit(UInt32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[E_UInteger,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_UInteger) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { Convert( ConvertChecked( Parameter( x type: E_UInteger ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[E_UInteger,System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_UInteger, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { TypeAs( Parameter( x type: E_UInteger ) type: System.Object ) } return type: System.Object type: System.Func`2[E_UInteger,System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_UInteger) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { Convert( Parameter( x type: E_UInteger ) type: System.Object ) } return type: System.Object type: System.Func`2[E_UInteger,System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_UInteger?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[E_UInteger],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_UInteger?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[E_UInteger],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(E_UInteger?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[E_UInteger],System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(E_UInteger?, E_UInteger?) -> E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { Parameter( x type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`2[System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- CLng(E_UInteger?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[E_UInteger],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(E_UInteger?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[E_UInteger],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_UInteger?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[E_UInteger],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_UInteger?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[E_UInteger],System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_UInteger?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.UInt32 ) method: System.Decimal op_Implicit(UInt32) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[E_UInteger],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_UInteger?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_UInteger],System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_UInteger?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { TypeAs( Parameter( x type: System.Nullable`1[E_UInteger] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_UInteger],System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_UInteger?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_UInteger],System.Object] ) -=-=-=-=-=-=-=-=- CByte(Long) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { ConvertChecked( Parameter( x type: System.Int64 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Int64,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Long) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { ConvertChecked( Parameter( x type: System.Int64 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Int64,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Long) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { ConvertChecked( Parameter( x type: System.Int64 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Int64,System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(Long, Long) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Parameter( x type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- CLng(Long) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Parameter( x type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Long) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Convert( Parameter( x type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Int64,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Long) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Convert( Parameter( x type: System.Int64 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Int64,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Long) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Convert( Parameter( x type: System.Int64 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Int64,System.Double] ) -=-=-=-=-=-=-=-=- CDec(Long) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Convert( Parameter( x type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Int64,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Long) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Convert( Parameter( x type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Int64,System.String] ) -=-=-=-=-=-=-=-=- TryCast(Long, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { TypeAs( Parameter( x type: System.Int64 ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Int64,System.Object] ) -=-=-=-=-=-=-=-=- CObj(Long) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Convert( Parameter( x type: System.Int64 ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Int64,System.Object] ) -=-=-=-=-=-=-=-=- CByte(Long?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.Int64],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Long?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.Int64],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Long?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.Int64],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Long?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { ConvertChecked( Parameter( x type: System.Nullable`1[System.Int64] ) Lifted type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.Int64],System.Int64] ) -=-=-=-=-=-=-=-=- DirectCast(Long?, Long?) -> Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { Parameter( x type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`2[System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- CBool(Long?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.Int64],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Long?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.Int64],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Long?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.Int64],System.Double] ) -=-=-=-=-=-=-=-=- CDec(Long?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.Int64],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Long?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Int64],System.String] ) -=-=-=-=-=-=-=-=- TryCast(Long?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.Int64] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Int64],System.Object] ) -=-=-=-=-=-=-=-=- CObj(Long?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { Convert( Parameter( x type: System.Nullable`1[System.Int64] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Int64],System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_Long) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { ConvertChecked( Parameter( x type: E_Long ) type: System.Byte ) } return type: System.Byte type: System.Func`2[E_Long,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_Long) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { ConvertChecked( Parameter( x type: E_Long ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[E_Long,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(E_Long) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { ConvertChecked( Parameter( x type: E_Long ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[E_Long,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(E_Long) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { ConvertChecked( Parameter( x type: E_Long ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[E_Long,System.Int64] ) -=-=-=-=-=-=-=-=- DirectCast(E_Long, E_Long) -> E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { Parameter( x type: E_Long ) } return type: E_Long type: System.Func`2[E_Long,E_Long] ) -=-=-=-=-=-=-=-=- CBool(E_Long) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { Convert( ConvertChecked( Parameter( x type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[E_Long,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_Long) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { Convert( Parameter( x type: E_Long ) type: System.Single ) } return type: System.Single type: System.Func`2[E_Long,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_Long) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { Convert( Parameter( x type: E_Long ) type: System.Double ) } return type: System.Double type: System.Func`2[E_Long,System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_Long) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { Convert( ConvertChecked( Parameter( x type: E_Long ) type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[E_Long,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_Long) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { Convert( ConvertChecked( Parameter( x type: E_Long ) type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[E_Long,System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_Long, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { TypeAs( Parameter( x type: E_Long ) type: System.Object ) } return type: System.Object type: System.Func`2[E_Long,System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_Long) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { Convert( Parameter( x type: E_Long ) type: System.Object ) } return type: System.Object type: System.Func`2[E_Long,System.Object] ) -=-=-=-=-=-=-=-=- CByte(E_Long?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[E_Long],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(E_Long?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[E_Long],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(E_Long?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[E_Long],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(E_Long?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[E_Long],System.Int64] ) -=-=-=-=-=-=-=-=- DirectCast(E_Long?, E_Long?) -> E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { Parameter( x type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`2[System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- CBool(E_Long?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[E_Long],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(E_Long?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[E_Long],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(E_Long?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { Convert( ConvertChecked( Parameter( x type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[E_Long],System.Double] ) -=-=-=-=-=-=-=-=- CDec(E_Long?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[E_Long],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(E_Long?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( x type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Long],System.String] ) -=-=-=-=-=-=-=-=- TryCast(E_Long?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { TypeAs( Parameter( x type: System.Nullable`1[E_Long] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_Long],System.Object] ) -=-=-=-=-=-=-=-=- CObj(E_Long?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[E_Long],System.Object] ) -=-=-=-=-=-=-=-=- CByte(Boolean) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Convert( Negate( Convert( Parameter( x type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Boolean,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Boolean) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Negate( ConvertChecked( Parameter( x type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Boolean,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Boolean) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Negate( ConvertChecked( Parameter( x type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Boolean,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Boolean) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Negate( ConvertChecked( Parameter( x type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Boolean,System.Int64] ) -=-=-=-=-=-=-=-=- DirectCast(Boolean, Boolean) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Parameter( x type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- CBool(Boolean) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Parameter( x type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Boolean) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Negate( Convert( Parameter( x type: System.Boolean ) type: System.Single ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Boolean,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Boolean) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Negate( Convert( Parameter( x type: System.Boolean ) type: System.Double ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Boolean,System.Double] ) -=-=-=-=-=-=-=-=- CDec(Boolean) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Convert( Parameter( x type: System.Boolean ) method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Boolean,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Boolean) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Convert( Parameter( x type: System.Boolean ) method: System.String ToString(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Boolean,System.String] ) -=-=-=-=-=-=-=-=- TryCast(Boolean, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { TypeAs( Parameter( x type: System.Boolean ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Boolean,System.Object] ) -=-=-=-=-=-=-=-=- CObj(Boolean) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Convert( Parameter( x type: System.Boolean ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Boolean,System.Object] ) -=-=-=-=-=-=-=-=- CByte(Boolean?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Convert( Negate( Convert( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.Boolean],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Boolean?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Negate( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.Boolean],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Boolean?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Negate( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.Boolean],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Boolean?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Negate( ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.Boolean],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Boolean?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) Lifted type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.Boolean],System.Boolean] ) -=-=-=-=-=-=-=-=- DirectCast(Boolean?, Boolean?) -> Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Parameter( x type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`2[System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- CSng(Boolean?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Negate( Convert( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Single ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.Boolean],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Boolean?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Negate( Convert( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Double ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.Boolean],System.Double] ) -=-=-=-=-=-=-=-=- CDec(Boolean?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.Boolean],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Boolean?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) method: System.String ToString(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Boolean],System.String] ) -=-=-=-=-=-=-=-=- TryCast(Boolean?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.Boolean] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Boolean],System.Object] ) -=-=-=-=-=-=-=-=- CObj(Boolean?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Boolean],System.Object] ) -=-=-=-=-=-=-=-=- CByte(Single) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { ConvertChecked( Parameter( x type: System.Single ) method: Byte ToByte(Single) in System.Convert type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Single,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Single) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { ConvertChecked( Parameter( x type: System.Single ) method: Int16 ToInt16(Single) in System.Convert type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Single,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Single) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { ConvertChecked( Parameter( x type: System.Single ) method: Int32 ToInt32(Single) in System.Convert type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Single,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Single) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { ConvertChecked( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Single,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Single) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { Convert( Parameter( x type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Single,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Single) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { Convert( Parameter( x type: System.Single ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Single,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Single) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { Convert( Parameter( x type: System.Single ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Single,System.Double] ) -=-=-=-=-=-=-=-=- CDec(Single) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { Convert( Parameter( x type: System.Single ) method: System.Decimal op_Explicit(Single) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Single,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Single) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { Convert( Parameter( x type: System.Single ) method: System.String ToString(Single) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Single,System.String] ) -=-=-=-=-=-=-=-=- TryCast(Single, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { TypeAs( Parameter( x type: System.Single ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Single,System.Object] ) -=-=-=-=-=-=-=-=- CObj(Single) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { Convert( Parameter( x type: System.Single ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Single,System.Object] ) -=-=-=-=-=-=-=-=- CByte(Single?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Single] ) method: Single op_Explicit(System.Nullable`1[System.Single]) in System.Nullable`1[System.Single] type: System.Single ) method: Byte ToByte(Single) in System.Convert type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.Single],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Single?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Single] ) method: Single op_Explicit(System.Nullable`1[System.Single]) in System.Nullable`1[System.Single] type: System.Single ) method: Int16 ToInt16(Single) in System.Convert type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.Single],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Single?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Single] ) method: Single op_Explicit(System.Nullable`1[System.Single]) in System.Nullable`1[System.Single] type: System.Single ) method: Int32 ToInt32(Single) in System.Convert type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.Single],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Single?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Single] ) method: Single op_Explicit(System.Nullable`1[System.Single]) in System.Nullable`1[System.Single] type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.Single],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Single?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Single] ) method: Single op_Explicit(System.Nullable`1[System.Single]) in System.Nullable`1[System.Single] type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.Single],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Single?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { Convert( Parameter( x type: System.Nullable`1[System.Single] ) Lifted type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.Single],System.Single] ) -=-=-=-=-=-=-=-=- DirectCast(Single?, Single?) -> Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { Parameter( x type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`2[System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- CDbl(Single?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Single] ) method: Single op_Explicit(System.Nullable`1[System.Single]) in System.Nullable`1[System.Single] type: System.Single ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.Single],System.Double] ) -=-=-=-=-=-=-=-=- CDec(Single?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Single] ) method: Single op_Explicit(System.Nullable`1[System.Single]) in System.Nullable`1[System.Single] type: System.Single ) method: System.Decimal op_Explicit(Single) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.Single],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Single?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Single] ) method: Single op_Explicit(System.Nullable`1[System.Single]) in System.Nullable`1[System.Single] type: System.Single ) method: System.String ToString(Single) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Single],System.String] ) -=-=-=-=-=-=-=-=- TryCast(Single?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.Single] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Single],System.Object] ) -=-=-=-=-=-=-=-=- CObj(Single?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { Convert( Parameter( x type: System.Nullable`1[System.Single] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Single],System.Object] ) -=-=-=-=-=-=-=-=- CByte(Double) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { ConvertChecked( Parameter( x type: System.Double ) method: Byte ToByte(Double) in System.Convert type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Double,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Double) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { ConvertChecked( Parameter( x type: System.Double ) method: Int16 ToInt16(Double) in System.Convert type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Double,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Double) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { ConvertChecked( Parameter( x type: System.Double ) method: Int32 ToInt32(Double) in System.Convert type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Double,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Double) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { ConvertChecked( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Double,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Double) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { Convert( Parameter( x type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Double,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Double) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { Convert( Parameter( x type: System.Double ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Double,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Double) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { Convert( Parameter( x type: System.Double ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Double,System.Double] ) -=-=-=-=-=-=-=-=- CDec(Double) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { Convert( Parameter( x type: System.Double ) method: System.Decimal op_Explicit(Double) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Double,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Double) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { Convert( Parameter( x type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Double,System.String] ) -=-=-=-=-=-=-=-=- TryCast(Double, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { TypeAs( Parameter( x type: System.Double ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Double,System.Object] ) -=-=-=-=-=-=-=-=- CObj(Double) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { Convert( Parameter( x type: System.Double ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Double,System.Object] ) -=-=-=-=-=-=-=-=- CByte(Double?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: Byte ToByte(Double) in System.Convert type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.Double],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Double?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: Int16 ToInt16(Double) in System.Convert type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.Double],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Double?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: Int32 ToInt32(Double) in System.Convert type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.Double],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Double?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.Double],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Double?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.Double],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Double?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.Double],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Double?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { Convert( Parameter( x type: System.Nullable`1[System.Double] ) Lifted type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.Double],System.Double] ) -=-=-=-=-=-=-=-=- DirectCast(Double?, Double?) -> Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { Parameter( x type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`2[System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- CDec(Double?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.Decimal op_Explicit(Double) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.Double],System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Double?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Double],System.String] ) -=-=-=-=-=-=-=-=- TryCast(Double?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.Double] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Double],System.Object] ) -=-=-=-=-=-=-=-=- CObj(Double?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { Convert( Parameter( x type: System.Nullable`1[System.Double] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Double],System.Object] ) -=-=-=-=-=-=-=-=- CByte(Decimal) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { ConvertChecked( Parameter( x type: System.Decimal ) method: Byte op_Explicit(System.Decimal) in System.Decimal type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Decimal,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Decimal) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { ConvertChecked( Parameter( x type: System.Decimal ) method: Int16 op_Explicit(System.Decimal) in System.Decimal type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Decimal,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Decimal) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { ConvertChecked( Parameter( x type: System.Decimal ) method: Int32 op_Explicit(System.Decimal) in System.Decimal type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Decimal,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Decimal) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { ConvertChecked( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Decimal,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Decimal) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { Convert( Parameter( x type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Decimal,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Decimal) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { Convert( Parameter( x type: System.Decimal ) method: Single op_Explicit(System.Decimal) in System.Decimal type: System.Single ) } return type: System.Single type: System.Func`2[System.Decimal,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Decimal) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { Convert( Parameter( x type: System.Decimal ) method: Double op_Explicit(System.Decimal) in System.Decimal type: System.Double ) } return type: System.Double type: System.Func`2[System.Decimal,System.Double] ) -=-=-=-=-=-=-=-=- DirectCast(Decimal, Decimal) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { Parameter( x type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- CDec(Decimal) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { Parameter( x type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- CStr(Decimal) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { Convert( Parameter( x type: System.Decimal ) method: System.String ToString(System.Decimal) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Decimal,System.String] ) -=-=-=-=-=-=-=-=- TryCast(Decimal, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { TypeAs( Parameter( x type: System.Decimal ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Decimal,System.Object] ) -=-=-=-=-=-=-=-=- CObj(Decimal) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { Convert( Parameter( x type: System.Decimal ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Decimal,System.Object] ) -=-=-=-=-=-=-=-=- CByte(Decimal?) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) method: System.Decimal op_Explicit(System.Nullable`1[System.Decimal]) in System.Nullable`1[System.Decimal] type: System.Decimal ) method: Byte op_Explicit(System.Decimal) in System.Decimal type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Nullable`1[System.Decimal],System.Byte] ) -=-=-=-=-=-=-=-=- CShort(Decimal?) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) method: System.Decimal op_Explicit(System.Nullable`1[System.Decimal]) in System.Nullable`1[System.Decimal] type: System.Decimal ) method: Int16 op_Explicit(System.Decimal) in System.Decimal type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Nullable`1[System.Decimal],System.Int16] ) -=-=-=-=-=-=-=-=- CInt(Decimal?) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) method: System.Decimal op_Explicit(System.Nullable`1[System.Decimal]) in System.Nullable`1[System.Decimal] type: System.Decimal ) method: Int32 op_Explicit(System.Decimal) in System.Decimal type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Nullable`1[System.Decimal],System.Int32] ) -=-=-=-=-=-=-=-=- CLng(Decimal?) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { ConvertChecked( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) method: System.Decimal op_Explicit(System.Nullable`1[System.Decimal]) in System.Nullable`1[System.Decimal] type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Nullable`1[System.Decimal],System.Int64] ) -=-=-=-=-=-=-=-=- CBool(Decimal?) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) method: System.Decimal op_Explicit(System.Nullable`1[System.Decimal]) in System.Nullable`1[System.Decimal] type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Nullable`1[System.Decimal],System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(Decimal?) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) method: System.Decimal op_Explicit(System.Nullable`1[System.Decimal]) in System.Nullable`1[System.Decimal] type: System.Decimal ) method: Single op_Explicit(System.Decimal) in System.Decimal type: System.Single ) } return type: System.Single type: System.Func`2[System.Nullable`1[System.Decimal],System.Single] ) -=-=-=-=-=-=-=-=- CDbl(Decimal?) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) method: System.Decimal op_Explicit(System.Nullable`1[System.Decimal]) in System.Nullable`1[System.Decimal] type: System.Decimal ) method: Double op_Explicit(System.Decimal) in System.Decimal type: System.Double ) } return type: System.Double type: System.Func`2[System.Nullable`1[System.Decimal],System.Double] ) -=-=-=-=-=-=-=-=- CDec(Decimal?) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Nullable`1[System.Decimal],System.Decimal] ) -=-=-=-=-=-=-=-=- DirectCast(Decimal?, Decimal?) -> Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { Parameter( x type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`2[System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- CStr(Decimal?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) method: System.Decimal op_Explicit(System.Nullable`1[System.Decimal]) in System.Nullable`1[System.Decimal] type: System.Decimal ) method: System.String ToString(System.Decimal) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Decimal],System.String] ) -=-=-=-=-=-=-=-=- TryCast(Decimal?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.Decimal] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Decimal],System.Object] ) -=-=-=-=-=-=-=-=- CObj(Decimal?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.Decimal],System.Object] ) -=-=-=-=-=-=-=-=- DirectCast(Date, Date) -> Date -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.DateTime ) body { Parameter( x type: System.DateTime ) } return type: System.DateTime type: System.Func`2[System.DateTime,System.DateTime] ) -=-=-=-=-=-=-=-=- CStr(Date) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.DateTime ) body { Convert( Parameter( x type: System.DateTime ) method: System.String ToString(System.DateTime) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.DateTime,System.String] ) -=-=-=-=-=-=-=-=- TryCast(Date, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.DateTime ) body { TypeAs( Parameter( x type: System.DateTime ) type: System.Object ) } return type: System.Object type: System.Func`2[System.DateTime,System.Object] ) -=-=-=-=-=-=-=-=- CObj(Date) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.DateTime ) body { Convert( Parameter( x type: System.DateTime ) type: System.Object ) } return type: System.Object type: System.Func`2[System.DateTime,System.Object] ) -=-=-=-=-=-=-=-=- DirectCast(Date?, Date?) -> Date? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.DateTime] ) body { Parameter( x type: System.Nullable`1[System.DateTime] ) } return type: System.Nullable`1[System.DateTime] type: System.Func`2[System.Nullable`1[System.DateTime],System.Nullable`1[System.DateTime]] ) -=-=-=-=-=-=-=-=- CStr(Date?) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.DateTime] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[System.DateTime] ) method: System.DateTime op_Explicit(System.Nullable`1[System.DateTime]) in System.Nullable`1[System.DateTime] type: System.DateTime ) method: System.String ToString(System.DateTime) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.DateTime],System.String] ) -=-=-=-=-=-=-=-=- TryCast(Date?, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.DateTime] ) body { TypeAs( Parameter( x type: System.Nullable`1[System.DateTime] ) type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.DateTime],System.Object] ) -=-=-=-=-=-=-=-=- CObj(Date?) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.DateTime] ) body { Convert( Parameter( x type: System.Nullable`1[System.DateTime] ) Lifted type: System.Object ) } return type: System.Object type: System.Func`2[System.Nullable`1[System.DateTime],System.Object] ) -=-=-=-=-=-=-=-=- CByte(String) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { ConvertChecked( Parameter( x type: System.String ) method: Byte ToByte(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Byte ) } return type: System.Byte type: System.Func`2[System.String,System.Byte] ) -=-=-=-=-=-=-=-=- CShort(String) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { ConvertChecked( Parameter( x type: System.String ) method: Int16 ToShort(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.String,System.Int16] ) -=-=-=-=-=-=-=-=- CInt(String) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { ConvertChecked( Parameter( x type: System.String ) method: Int32 ToInteger(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.String,System.Int32] ) -=-=-=-=-=-=-=-=- CLng(String) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { ConvertChecked( Parameter( x type: System.String ) method: Int64 ToLong(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.String,System.Int64] ) -=-=-=-=-=-=-=-=- CBool(String) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Parameter( x type: System.String ) method: Boolean ToBoolean(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.String,System.Boolean] ) -=-=-=-=-=-=-=-=- CSng(String) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Parameter( x type: System.String ) method: Single ToSingle(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Single ) } return type: System.Single type: System.Func`2[System.String,System.Single] ) -=-=-=-=-=-=-=-=- CDbl(String) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) } return type: System.Double type: System.Func`2[System.String,System.Double] ) -=-=-=-=-=-=-=-=- CDec(String) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Parameter( x type: System.String ) method: System.Decimal ToDecimal(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.String,System.Decimal] ) -=-=-=-=-=-=-=-=- CDate(String) -> Date -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Parameter( x type: System.String ) method: System.DateTime ToDate(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.DateTime ) } return type: System.DateTime type: System.Func`2[System.String,System.DateTime] ) -=-=-=-=-=-=-=-=- DirectCast(String, String) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Parameter( x type: System.String ) } return type: System.String type: System.Func`2[System.String,System.String] ) -=-=-=-=-=-=-=-=- CStr(String) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Parameter( x type: System.String ) } return type: System.String type: System.Func`2[System.String,System.String] ) -=-=-=-=-=-=-=-=- DirectCast(String, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Parameter( x type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`2[System.String,System.Object] ) -=-=-=-=-=-=-=-=- TryCast(String, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Parameter( x type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`2[System.String,System.Object] ) -=-=-=-=-=-=-=-=- CObj(String) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Parameter( x type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`2[System.String,System.Object] ) -=-=-=-=-=-=-=-=- DirectCast(Object, SByte) -> SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.SByte ) } return type: System.SByte type: System.Func`2[System.Object,System.SByte] ) -=-=-=-=-=-=-=-=- DirectCast(Object, SByte?) -> SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`2[System.Object,System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_SByte) -> E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: E_SByte ) } return type: E_SByte type: System.Func`2[System.Object,E_SByte] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_SByte?) -> E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`2[System.Object,System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Byte) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Object,System.Byte] ) -=-=-=-=-=-=-=-=- CByte(Object) -> Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { ConvertChecked( Parameter( x type: System.Object ) method: Byte ToByte(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Object,System.Byte] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Byte?) -> Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`2[System.Object,System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_Byte) -> E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: E_Byte ) } return type: E_Byte type: System.Func`2[System.Object,E_Byte] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_Byte?) -> E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`2[System.Object,System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Short) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Object,System.Int16] ) -=-=-=-=-=-=-=-=- CShort(Object) -> Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { ConvertChecked( Parameter( x type: System.Object ) method: Int16 ToShort(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Object,System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Short?) -> Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`2[System.Object,System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_Short) -> E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: E_Short ) } return type: E_Short type: System.Func`2[System.Object,E_Short] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_Short?) -> E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`2[System.Object,System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, UShort) -> UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.UInt16 ) } return type: System.UInt16 type: System.Func`2[System.Object,System.UInt16] ) -=-=-=-=-=-=-=-=- DirectCast(Object, UShort?) -> UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`2[System.Object,System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_UShort) -> E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: E_UShort ) } return type: E_UShort type: System.Func`2[System.Object,E_UShort] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_UShort?) -> E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`2[System.Object,System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Integer) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Object,System.Int32] ) -=-=-=-=-=-=-=-=- CInt(Object) -> Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { ConvertChecked( Parameter( x type: System.Object ) method: Int32 ToInteger(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Object,System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Integer?) -> Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`2[System.Object,System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_Integer) -> E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: E_Integer ) } return type: E_Integer type: System.Func`2[System.Object,E_Integer] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_Integer?) -> E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`2[System.Object,System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, UInteger) -> UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.UInt32 ) } return type: System.UInt32 type: System.Func`2[System.Object,System.UInt32] ) -=-=-=-=-=-=-=-=- DirectCast(Object, UInteger?) -> UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`2[System.Object,System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_UInteger) -> E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: E_UInteger ) } return type: E_UInteger type: System.Func`2[System.Object,E_UInteger] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_UInteger?) -> E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`2[System.Object,System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Long) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Object,System.Int64] ) -=-=-=-=-=-=-=-=- CLng(Object) -> Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { ConvertChecked( Parameter( x type: System.Object ) method: Int64 ToLong(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Object,System.Int64] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Long?) -> Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`2[System.Object,System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_Long) -> E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: E_Long ) } return type: E_Long type: System.Func`2[System.Object,E_Long] ) -=-=-=-=-=-=-=-=- DirectCast(Object, E_Long?) -> E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`2[System.Object,System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Boolean) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Object,System.Boolean] ) -=-=-=-=-=-=-=-=- CBool(Object) -> Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) method: Boolean ToBoolean(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Object,System.Boolean] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Boolean?) -> Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`2[System.Object,System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Single) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Object,System.Single] ) -=-=-=-=-=-=-=-=- CSng(Object) -> Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) method: Single ToSingle(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Single ) } return type: System.Single type: System.Func`2[System.Object,System.Single] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Single?) -> Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`2[System.Object,System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Double) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Object,System.Double] ) -=-=-=-=-=-=-=-=- CDbl(Object) -> Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) method: Double ToDouble(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) } return type: System.Double type: System.Func`2[System.Object,System.Double] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Double?) -> Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`2[System.Object,System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Decimal) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Object,System.Decimal] ) -=-=-=-=-=-=-=-=- CDec(Object) -> Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) method: System.Decimal ToDecimal(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Object,System.Decimal] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Decimal?) -> Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`2[System.Object,System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Date) -> Date -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.DateTime ) } return type: System.DateTime type: System.Func`2[System.Object,System.DateTime] ) -=-=-=-=-=-=-=-=- CDate(Object) -> Date -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) method: System.DateTime ToDate(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.DateTime ) } return type: System.DateTime type: System.Func`2[System.Object,System.DateTime] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Date?) -> Date? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) Lifted LiftedToNull type: System.Nullable`1[System.DateTime] ) } return type: System.Nullable`1[System.DateTime] type: System.Func`2[System.Object,System.Nullable`1[System.DateTime]] ) -=-=-=-=-=-=-=-=- DirectCast(Object, String) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) type: System.String ) } return type: System.String type: System.Func`2[System.Object,System.String] ) -=-=-=-=-=-=-=-=- CStr(Object) -> String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Convert( Parameter( x type: System.Object ) method: System.String ToString(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Object,System.String] ) -=-=-=-=-=-=-=-=- DirectCast(Object, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Parameter( x type: System.Object ) } return type: System.Object type: System.Func`2[System.Object,System.Object] ) -=-=-=-=-=-=-=-=- TryCast(Object, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Parameter( x type: System.Object ) } return type: System.Object type: System.Func`2[System.Object,System.Object] ) -=-=-=-=-=-=-=-=- CObj(Object) -> Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Parameter( x type: System.Object ) } return type: System.Object type: System.Func`2[System.Object,System.Object] )
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Test/PdbUtilities/Shared/StringUtilities.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.Globalization; using System.Text; namespace Roslyn.Test { internal static class StringUtilities { internal static string EscapeNonPrintableCharacters(string str) { StringBuilder sb = new StringBuilder(); foreach (char c in str) { bool escape; switch (CharUnicodeInfo.GetUnicodeCategory(c)) { case UnicodeCategory.Control: case UnicodeCategory.OtherNotAssigned: case UnicodeCategory.ParagraphSeparator: case UnicodeCategory.Surrogate: escape = true; break; default: escape = c >= 0xFFFC; break; } if (escape) { sb.AppendFormat("\\u{0:X4}", (int)c); } else { sb.Append(c); } } return sb.ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Globalization; using System.Text; namespace Roslyn.Test { internal static class StringUtilities { internal static string EscapeNonPrintableCharacters(string str) { StringBuilder sb = new StringBuilder(); foreach (char c in str) { bool escape; switch (CharUnicodeInfo.GetUnicodeCategory(c)) { case UnicodeCategory.Control: case UnicodeCategory.OtherNotAssigned: case UnicodeCategory.ParagraphSeparator: case UnicodeCategory.Surrogate: escape = true; break; default: escape = c >= 0xFFFC; break; } if (escape) { sb.AppendFormat("\\u{0:X4}", (int)c); } else { sb.Append(c); } } return sb.ToString(); } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicCallReducer.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.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicCallReducer Private Class Rewriter Inherits AbstractReductionRewriter Public Sub New(pool As ObjectPool(Of IReductionRewriter)) MyBase.New(pool) End Sub Public Overrides Function VisitCallStatement(node As CallStatementSyntax) As SyntaxNode Return SimplifyStatement( node, newNode:=MyBase.VisitCallStatement(node), simplifier:=s_simplifyCallStatement) End Function Public Overrides Function VisitParenthesizedExpression(node As ParenthesizedExpressionSyntax) As SyntaxNode Return SimplifyExpression( node, newNode:=MyBase.VisitParenthesizedExpression(node), simplifier:=s_reduceParentheses) 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.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicCallReducer Private Class Rewriter Inherits AbstractReductionRewriter Public Sub New(pool As ObjectPool(Of IReductionRewriter)) MyBase.New(pool) End Sub Public Overrides Function VisitCallStatement(node As CallStatementSyntax) As SyntaxNode Return SimplifyStatement( node, newNode:=MyBase.VisitCallStatement(node), simplifier:=s_simplifyCallStatement) End Function Public Overrides Function VisitParenthesizedExpression(node As ParenthesizedExpressionSyntax) As SyntaxNode Return SimplifyExpression( node, newNode:=MyBase.VisitParenthesizedExpression(node), simplifier:=s_reduceParentheses) End Function End Class End Class End Namespace
-1